【发布时间】:2019-10-07 09:39:42
【问题描述】:
从 ifstream 读取文本文件以将每一行保存到字符串向量后,应该使用 for 循环打印出来,但它只在 cout 末尾没有换行符时显示最后一行。
我尝试了两种情况来打印字符串向量:
1)cout << s;
2)cout << s << '\n';
其中 s 是迭代每个循环的向量的字符串。
1) 只显示最后一行,而2) 显示整个文本。
ifstream inFile("sample.txt");
string str;
vector<string> strings;
while (getline(inFile, str))
strings.push_back(str);
for (auto s : strings)
std::cout << s;
示例文本是:
Test File
The quick brown fox jumps over the lazy dog.
cout << s; 仅打印:
The quick brown fox jumps over the lazy dog.
cout << s << '\n'; 打印:
Test File
The quick brown fox jumps over the lazy dog.
在执行第一个案例时,我期望得到第二个结果。 除了换行符本身,换行符如何改变输出结果?
已编辑:
由于getline() 在到达换行符时停止并且不读取换行符,所以没有\n 的cout 应该打印Test FileThe quick brown fox jumps over the lazy dog if 程序在 Windows 上执行。因为ifstream 在text 模式下工作,该模式将\r\n 转换为\n。
但是,由于我使用的是安装在 cygwin 上的 g++,所以这不太可能发生。这就是Test File\r\nThe quick brown fox jumps over the lazy dog 只显示The quick brown fox jumps over the lazy dog 的原因。
简单地说,\r 使输出行回到原点,并截断了\r 之前的文本。
【问题讨论】:
-
第一段代码将所有内容打印在一行中。它没有理由跳过任何行。
-
@RSahu 不幸的是,它做到了。我在 Windows 和 Debian 上都试过了。
-
见this anwer。您可能面临与该问题的 OP 相同的问题。
-
如果您在输入文件中翻转行,输出很可能是
Test File brown fox jumps over the lazy dog. -
@RSahu 是的。正确的。我刚刚在 linux 上再次尝试通过创建具有确切文本的确切文件并且它起作用了。我在 linux 上用于测试的文件只是从 Windows 上创建的文件中复制而来的。我认为这是因为 Windows 使用
\r\n换行,而类 UNIX 系统使用\n换行。
标签: c++ cygwin newline cout carriage-return