0

This function is supposed to open a .txt file like this:

1    4    5 

2    4    6

etc. (with tab between numbers)

and save each number in one variable

void Graph::readData(char* fname)
{
    //cout<<"1";
    int x,y,w;//assistant variables
    ifstream input;//stream for reading file
    input.open(fname,ios::in);
    if(!input)
    {
        cerr<<"Input file doesn't exist"<<endl;//error if file doens exist
    }
    else
    {
        cout<<"Input file opened"<<endl;
        cout<<"Reading Data from file..."<<endl;
        while(!input.eof())//till the end of file
        {
            input>>x>>y>>w;//reads the links-site
            cout<<"x: "<<x<<"y:"<<y<<"w: "<<w<<endl;
            insertLink(x,y,w);//inserts them

        }
        input.close();//closing file
    }
}

However, when I "cout" the results I get something like this:

x=1  y=  w=5

x=2  y=  w=6

without y!

Why could this happen?

PS: In addition, eof() becomes true after the file is finished (reads one extra line). How can I stop while iteration properly?

This is the file I'm trying to read from: http://www.speedyshare.com/tpvuD/input.txt

syfantid
  • 357
  • 3
  • 18
  • Regarding your PS: [Why is `iostream::eof` inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – WhozCraig Feb 14 '14 at 16:49
  • 1
    Apart from `eof` check, the code should work, which means that the error is in the code you're not showing us or that input file isn't in the format you said it is. – jrok Feb 14 '14 at 16:56
  • "...when I 'cout' the results..." those results aren't from the output loop in this posted code. For starters, the posted code has colons (`:`), not equals (`=`). Whatever you're claiming is improper output, it isn't from that loop. My crystal ball tells me the code that *is* writing your output never sends the y-value to the output stream, but without seeing the *real* code, its impossible to say for sure. [That loop works](http://ideone.com/UXZ6I9) once you fix the erroneous while-condition. – WhozCraig Feb 14 '14 at 16:58
  • "=" was my... " mistake... http://s12.postimg.org/591imz659/Screenshot_35.png These are the results I get! – syfantid Feb 14 '14 at 17:03
  • Search StackOverflow for "c++ read file integer parse" – Thomas Matthews Feb 14 '14 at 19:22

1 Answers1

1

To stop the iteration properly, write the loop as:

while(input>>x>>y>>w)//till the end of file
{ /* ... */ }

Do not check input.eof().

timrau
  • 21,494
  • 4
  • 47
  • 62