I want to read the contents of a file and input them as variables. I have written this code:

while (!numbersList.eof())
{
    numbersList >> type >> num1 >> num2;
    Complex *object = new Complex(type,num1,num2);
    cout << "For line number " << n << ": " << endl;
    object->printAll();
    cout << endl;
    n++;
}

The only problem I am getting is that it prints out the last line in the file twice. For example, the file has 4 lines thusly:

p 100 0.80
r 50 50
p 20 4.8
r -100 25

but the result for the 'r -100 25' line is printed twice.

I tried using

while (numbersList >> type >> num1 >> num2)

but that only printed the first and third lines of the file...

Very stuck on this, any help much appreciated!

Conventional wisdom seems to be that trying to read data from a file (or the console) directly as formated data leads to issues detecting end of file/ bad data. You should read the file line by line and then for each line process it into the data you are expecting to receive.

Pseudo code something like

while(getline from file)
{
  if line is not blank/empty
  {
     put line into (i)stringstream

     read data from stringstream

     if (stringstream good (i.e. no errors reading the data))
     {
         process data
     }
  }
}

Thanks, I think I get what you're saying.

By stringstream do you just mean a normal string?

Also, could you explain why

while (numbersList >> type >> num1 >> num2)

didn't work?

Thanks a lot mate :)

It didn't work because you did something like this:

while (numbersList >> type >> num1 >> num2) // you read a line here
{
    Complex *object = new Complex(type,num1,num2);
    numbersList >> type >> num1 >> num2; // and then you read another line here
    cout << "For line number " << n << ": " << endl;
    object->printAll();
    cout << endl;
    n++;
}

It will work fine if you do it like this:

while (numbersList >> type >> num1 >> num2)
{
    Complex *object = new Complex(type,num1,num2);
    // numbersList >> type >> num1 >> num2;
    cout << "For line number " << n << ": " << endl;
    object->printAll();
    cout << endl;
    n++;
}

Also, you don't really need dynamic memory allocation here, if you only want to print the contents of the file. This would work fine:

while (numbersList >> type >> num1 >> num2)
{
    cout << "For line number " << n << ": " << endl;
    Complex(type,num1,num2).printAll();
    cout << endl;
    n++;
}

Edited 4 Years Ago by m4ster_r0shi

This article has been dead for over six months. Start a new discussion instead.