我正在尝试编写一个非常简单的程序,逐行读取其标准输入(直到“ end”出现在一行的开头)。同时,它尝试构造一个包含所有行串联的新字符串。
这种行为令人费解。正确读取了这些cout << current << endl
行(如该行所示)。但是,构造的字符串不是我期望的。相反,它仅包含最后读取的内容。但是,如果我替换construct.append(current)
为construct.append("foo")
,它就可以很好地工作。
我在这里做错了什么?
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
int main() {
string construct;
while(true) {
string current;
getline(cin, current);
assert(!cin.eof());
if (current.find("end") == 0) { break; }
cout << current << endl;
construct.append(current);
}
cout << construct << endl;
return 0;
}
编译:
g++ -o main main.cpp -Wall -std=c++0x
输入: input.txt
abcdef
ghij
end
输出: ./main < input.txt
abcdef
ghij
ghijef
如果我键入输入而不是使用文件,则它将按预期工作。同样,我在gcc(linux)和clang(mac os)上也得到了相同的结果。
我发现了问题。我的输入文件是带有CRLF行终止符的ascii文件(并且我使用的是Mac)。该construct
变量被正确创建,但它不是由终端正确显示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句