Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...