C++获取行并追加

C++ getline and append

本文关键字:追加 获取 C++      更新时间:2023-10-16

我正试图编写一个非常简单的程序,逐行读取其标准输入(直到"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;
}