Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ' ' (0x0d).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...