[英]C++ getline and append
我正在嘗試編寫一個非常簡單的程序,逐行讀取其標准輸入(直到“ end”出現在一行的開頭)。 同時,它嘗試構造一個包含所有行串聯的新字符串。
這種行為令人費解。 正確讀取了這些行(如cout << current << endl
行所示)。 但是,構造的字符串不是我期望的。 相反,它僅包含最后讀取的內容。 但是,如果我用construct.append(current)
construct.append("foo")
替換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
變量已正確創建,但終端未正確顯示。
我將我的.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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.