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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…