【问题标题】:C++ getline and appendC++ getline 和追加
【发布时间】: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 &lt; input.txt

abcdef
ghij
ghijef

如果我键入输入而不是使用文件,它会按预期工作。我也得到了与 gcc (linux) 和 clang (mac os) 相同的结果。

【问题讨论】:

  • Works for me。我们可以看看一些示例输入和输出吗?
  • 在 Visual Studio 2010 Express 中也能正常工作..
  • 我遇到了同样的问题。在 Cygwin 中它只显示最后一行,但在 Netbeans 中它显示整个内容。非常令人沮丧。

标签: c++ string append


【解决方案1】:

我将 .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;
}

【讨论】:

    【解决方案2】:

    我发现了问题。我的输入文件是一个带有 CRLF 行终止符的 ascii 文件(我使用的是 mac)。 construct 变量已正确创建,但终端未正确显示。

    【讨论】:

      猜你喜欢
      • 2013-06-02
      • 2013-04-28
      • 1970-01-01
      • 2018-09-18
      • 2013-05-27
      • 2019-05-03
      • 2016-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多