简体   繁体   中英

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

I've been having trouble with reading text files in c++, particularly when assigning a line to a variable.

I have the following code:

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));

When it does the cout << linha << endl; it returns something like :

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

I've googled it quite a lot and can't find an answer. I'm new to C++ so don't bash too much xD

Don't do this:

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;
}

But the better design is:

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

You are failing to move past the comma:

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 has a getline function, it accepts a char* as the first parameter and the maximum length as the second.

ifstream also has operator>> which you should be using for input, but it will read till whitespace, which is not what you want.

::getline that you're using should also work, but that's assuming that the stream is OK, which as mentioned before, you don't check correctly. You should be checking for errors after calling it, because if you reach EOF or there's an error, you won't know until the whole loop is done.

Also, what's in the file? Maybe what you're getting is the correct result?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM