【问题标题】:[C++]Importing text file - Problems with getline()[C++]导入文本文件 - getline() 的问题
【发布时间】:2011-10-23 21:12:53
【问题描述】:

我在用 c++ 读取文本文件时遇到了麻烦,尤其是在将一行分配给变量时。

我有以下代码:

ifstream fx;
fx.open(nomeFich);
if(!fx)
{cout << "FX. nao existe!" <<endl;}
string linha="";;
int pos, inic;

while(!fx.eof())
{
    getline(fx,linha);

    if(linha.size() > 0)
    {
        cout << linha << endl;
        inic=0;
        pos=0;
        pos=linha.find(",",inic);
        cout << pos << endl;
        string nomeL1(linha.substr(inic,pos));
        cout << "atribuiu 1" << endl;
        inic=pos;

        cout <<"inic: " << inic << "      pos:" << pos <<endl;

        pos=linha.find(',',inic);
        string nomeL2(linha.substr(inic,pos));
        cout << "atribuiu 2" << endl;
        inic=pos;

        cout <<"inic: " << inic << "      pos:" << pos <<endl;

        pos=linha.find(',',inic);
        cout << "atribuiu 3" << endl;
        string dist(linha.substr(inic,pos));

当它执行cout &lt;&lt; linha &lt;&lt; endl; 时,它会返回类似:

===============================

我用谷歌搜索了很多,但找不到答案。 我是 C++ 新手,所以不要过多抨击 xD

【问题讨论】:

  • 为什么不使用fx.getline()
  • 喜欢 linha=fx.getline();?它给出了一个错误..
  • fx &gt;&gt; linha; 在我们的过程中。
  • 您将处理太多行,因为在您读取文件末尾之前不会设置 eof。使用while( getline( fx, linha ) ) { }

标签: c++ file text import


【解决方案1】:

不要这样做:

while(!fx.eof())
{
    getline(fx,linha);   // Here you have to check if getline() actually succeded
                         // before you do any further processing.
                         // You could add if (!fx) { break;}

    // STUFF;
}

但更好的设计是:

while(getline(fx,linha))  // If the read works then enter the loop otherwise don't
{
    // STUFF
}

你没有跳过逗号:

inic=pos;                  // pos is the position of the last ',' or std::string::npos
pos=linha.find(',',inic);  // So here pos will be the same as last time.
                           // As you start searching from a position that has a comma.

【讨论】:

    【解决方案2】:

    ifstream 有一个getline 函数,它接受char* 作为第一个参数,最大长度作为第二个参数。

    ifstream 也有 operator&gt;&gt;,您应该将其用于输入,但它会一直读取到空格,这不是您想要的。

    您正在使用的::getline 也应该可以工作,但这是假设流是正常的,如前所述,您没有正确检查。你应该在调用它之后检查错误,因为如果你到达 EOF 或者有一个错误,你不会知道直到整个循环完成。

    另外,文件里有什么?也许你得到的是正确的结果?

    【讨论】:

    • 我不想使用与 char 关联的 getline,因为我现在不完全了解行的长度。我有一个 txt 文件,其中包含以下内容: Lisboa,Porto,300 Faro,Porto,600 Porto,Faro,600 Maia,Porto,50 Porto,Covilha,150 想法是使用逗号将行分隔为三个字符串变量一个分隔符。尝试了 Ed S. 以及 little adv 的建议,但没有成功,还是一样..
    • 如何检查调用它的错误?
    • @NunoNeto 它返回对流的引用,所以你可以在返回值上使用!
    猜你喜欢
    • 2016-07-29
    • 2020-06-11
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2016-02-13
    相关资源
    最近更新 更多