简体   繁体   中英

Inconsistent std::cout behavior

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM