【发布时间】:2015-05-24 23:58:26
【问题描述】:
我正在尝试编写一个非常简单的程序,逐行读取其标准输入(直到“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) 相同的结果。
【问题讨论】:
-
Works for me。我们可以看看一些示例输入和输出吗?
-
在 Visual Studio 2010 Express 中也能正常工作..
-
我遇到了同样的问题。在 Cygwin 中它只显示最后一行,但在 Netbeans 中它显示整个内容。非常令人沮丧。