C++获取行并追加
C++ getline and append
我正试图编写一个非常简单的程序,逐行读取其标准输入(直到"end"出现在一行的开头)。同时,它试图构造一个新的字符串,该字符串包含所有行的串联。
这种行为令人费解。行被正确读取(如cout << current << endl
行所示)。然而,构造的字符串并不是我所期望的。相反,它只包含最后一次读取。然而,如果我用construct.append("foo")
替换construct.append(current)
,它可以很好地工作。
我在这里做错了什么?
#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(macos)上也得到了相同的结果。
我发现了问题。我的输入文件是一个带有CRLF行终止符的ascii文件(我使用的是mac)。construct
变量创建正确,但终端未正确显示。
我将.txt文件的内容复制到Word,并删除了所有硬返回,这很有效,但这并不总是理想或可能的。字符编码似乎没有影响。当我添加换行符和字符串时,解决了这个问题。
Text::Text(string file) {
ifstream in;
string line;
in.open( file.c_str() ); // because the file name is a parameter decided at runtime in my code
while(getline(in,line,'n')){
fileContents.append(line+"n"); // fixed by adding "n" here
}
cout << "n Final product:n";
cout << fileContents;
}
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 从C字符串中获取奇怪的字符串长度
- 为什么我的for循环不能正确获取argv
- 从python中调用C++函数并获取返回值
- 如何获取一个数字的前3位
- 获取字符串的长度并将其分配给数组
- 无法获取菜单选择以运行函数.C++
- 数组长度,为什么从命令行获取时不能使用它?
- Boost Spirit,获取迭代器内部语义动作
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 具有默认值的引用获取函数
- C++获取行并追加
- 如何在mongo-c-driver或mongocxx驱动程序中追加文档后获取_id