C++ 不一致的std::cout行为

C++ 不一致的std::cout行为,c++,cout,C++,Cout,在打印多个内容时,std::cout似乎无法保持一致,如下两个示例所示。我认为这可能与缓冲区刷新有关,但即使在测试示例中添加了一些std::flush,也没有什么区别 #include <cstdlib> #include <iostream> #include <str

在打印多个内容时,
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();
}
在屏幕上,但实际输出是

aaa 
a
我用它来编译

g++ -g -std=c++11 -o test test.cpp

g++的版本是5.2.0

我感觉马克·兰森的评论指出了问题所在。您可以通过以二进制模式打开文件并打印编码字符的整数值来验证该假设

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();
}
如果您的平台不是Windows,那么您得到的输出将是有意义的

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


回车符(
'\r'
)会导致在上一个输出的顶部写入该行。

您希望得到什么输出?实际产量是多少?输入是什么?另外,请发布可编译的代码。我希望得到相同的输出,即“aaa”,因为在这两种情况下,字符串在cout语句中重复了三次。你真的读过我的评论吗?我猜文件实际上有两个字符,
'a'
'\x0d'
@MarkRansom为什么没有三个<代码>a\n\r?
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();
}
61
0d
0a