[C ++]导入文本文件 - getline()问题

时间:2011-10-23 21:12:53

标签: c++ file text import

我在使用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 << linha << endl;时,它会返回如下内容:

  

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

我用Google搜索了很多内容,无法找到答案。 我是C ++的新手,所以不要过多地使用xD

2 个答案:

答案 0 :(得分:2)

不要这样做:

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.

答案 1 :(得分:0)

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

ifstream也有operator>>你应该用它来输入,但它会读到空白,这不是你想要的。

您正在使用的

::getline也应该有效,但是假设流是正常的,如前所述,您没有正确检查。你应该在调用之后检查错误,因为如果你达到EOF或者出现错误,你将无法知道,直到整个循环完成。

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