Inconsistent std::cout behavior

与世无争的帅哥 提交于 2019-12-13 08:15:48

问题


I seems std::cout does not work consistently in printing multiple things, as shown in the following two examples. I thought it might related to buffer flush but it made no difference even if I add a number of std::flush in the test example.

#include <cstdlib>                                                                                                   
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>

void test(const std::string& f1);

int main(void) {
    std::string a = "a";
    std::cout << a <<  a << a << std::endl; 
    // Then I got aaa on the screen, which is as expected. 

    test("inputfile");
    // The input file contains one character: "a" 
    // after running the test I got only one "a" on the screen
    // even though the string is repeated three times in the cout statement, as in the previous case
    return 0;
}

void test(const std::string& f1){
    std::ifstream ifile;
    ifile.open(f1);

    for(std::string line; std::getline(ifile, line); ) {
        std::cout << line <<  line << line << std::endl;
    }
    ifile.close();
}

I expected to see

aaa     
aaa 

on the screen, but the actual output was

aaa 
a

I use this to compile

g++ -g -std=c++11 -o test test.cpp

The version of g++ is 5.2.0.


回答1:


I have a feeling the comment by Mark Ransom points out the problem. You can verify that hypothesis by opening your file in binary mode and printing the integer values that encode the characters.

void test(const std::string& f1){
    std::ifstream ifile;
    ifile.open(f1, std::ifstream::binary);

    int ch;
    while ( (ch = ifile.get()) != EOF )
    {
       // Print the integer value that encodes the character
       std::cout << std::setw(2) << std::setfill('0') << std::hex << ch << std::endl;
    }
    ifile.close();
}

If the output is

61
0d
0a

and your platform is not Windows, then the output your are getting would make sense.

The line read from the file contains the characters 'a' (0x61) and '\r' (0x0d).

The carriage return character ('\r') causes the line to be written on top of the previous output.



来源:https://stackoverflow.com/questions/42589903/inconsistent-stdcout-behavior

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!