std :: cout行为不一致

lin*_*usz -1 c++ cout

我似乎std::cout在打印多个内容时不能始终如一地工作,如以下两个示例所示.我认为它可能与缓冲区刷新有关,但即使我std::flush在测试示例中添加了一些数据也没有任何区别.

#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();
}
Run Code Online (Sandbox Code Playgroud)

我期望看到

aaa     
aaa 
Run Code Online (Sandbox Code Playgroud)

在屏幕上,但实际输出是

aaa 
a
Run Code Online (Sandbox Code Playgroud)

我用它来编译

g++ -g -std=c++11 -o test test.cpp
Run Code Online (Sandbox Code Playgroud)

g ++的版本是5.2.0.

R S*_*ahu 5

我有一种感觉Mark Ransom的评论指出了这个问题.您可以通过以二进制模式打开文件并打印编码字符的整数值来验证该假设.

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();
}
Run Code Online (Sandbox Code Playgroud)

如果输出是

61
0d
0a
Run Code Online (Sandbox Code Playgroud)

并且您的平台不是Windows,那么您获得的输出将是有意义的.

从文件中读取的行包含字符'a'(0x61)和'\r'(0x0d).

回车符(\n '\r')使得行被写在上一个输出的顶部.