Nathan Brown
Nathan Brown

Reputation: 15

Why does the loop with C++ io streams break after first iteration?

This is the code I have so far. I am getting my data from an input file. The file has all the data that I need for each variable that I am calling but when I run it I only get one iteration and it exits the loop after that. I need it to run till it reaches the end of the file.

#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;

int main ()
{
    ifstream pTemp("PlanetCelsius.dat");
    int pNumber, pSize;
    string pName;
    double cTemp, fTemp;

    cout << "Number\t" << "Planet Name\t" << "Diameter\t" << "Celsius\t" << "Fahrenheit" << endl;

        while (pTemp >> pNumber) 
        {
            while (pTemp >> pName) 
            {
                while (pTemp >> pSize) 
                {
                    while (pTemp >> cTemp) 
                    {
                        pTemp >> pNumber;
                        cout << pNumber << " ";
                    }
                pTemp >> pName;
            cout << pName << " ";
                }
        pTemp >> pSize;
        cout << pSize << " ";
            }
    pTemp >> cTemp;
    fTemp = 9 * (cTemp) / 5 + 32;
    cout << cTemp << " " << fTemp << endl;
        }

    system ("PAUSE");
        return 0;
}

Upvotes: 0

Views: 232

Answers (2)

Johnny Pauling
Johnny Pauling

Reputation: 13437

You're doing:

while(there's a number)
  while(there's a string)
    while(there's a number)
     while(there's a number)
     take first number
    take first string
  take first number
take first number

and your program fetches all the numbers it can in the inner-most while loop messing with your number-string-number-number sequence.

When the first while is checked for the second time, it cannot find a number because the inner-most loop already fetched every number till the first string and it exits.

Using while()s is a bad choice, try to parse the file as spin_eight suggested.

Upvotes: 0

spin_eight
spin_eight

Reputation: 4025

while (cin.good)
{
    pTemp >> pNumber >> pName >> pSize >> cTemp >> pNumber;
    cout << pNumber << " " << pName << " " << pSize << " ";
    fTemp = 9 * (cTemp) / 5 + 32;
    cout << cTemp << " " << fTemp << endl;

}
return 0;

I haven`t seen your file structure, but I gues this code snippet will work.

Upvotes: 1

Related Questions