不一致的 std::cout 行为
Inconsistent std::cout behavior
我似乎 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
aaa
在屏幕上,但实际输出是
aaa
a
我用这个编译
g++ -g -std=c++11 -o test test.cpp
g++版本为5.2.0。
我感觉 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();
}
如果输出是
61
0d
0a
并且您的平台不是 Windows,那么您得到的输出是有意义的。
从文件中读取的行包含字符 'a'
(0x61
) 和 '\r'
(0x0d
).
回车 return 字符 ('\r'
) 导致该行被写在前一个输出的顶部。
我似乎 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
aaa
在屏幕上,但实际输出是
aaa
a
我用这个编译
g++ -g -std=c++11 -o test test.cpp
g++版本为5.2.0。
我感觉 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();
}
如果输出是
61
0d
0a
并且您的平台不是 Windows,那么您得到的输出是有意义的。
从文件中读取的行包含字符 'a'
(0x61
) 和 '\r'
(0x0d
).
回车 return 字符 ('\r'
) 导致该行被写在前一个输出的顶部。