使用getline()导入文本的问题

[C++]Importing text Problems with getline()

本文关键字:文本 问题 导入 getline 使用      更新时间:2023-10-16

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

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

我在谷歌上搜索了很多次,都找不到答案。我刚开始学c++,所以不要太乱敲xD

不要这样做:

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.

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

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

您正在使用的

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

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