0

这是我到目前为止的代码。我正在从输入文件中获取数据。该文件包含我调用的每个变量所需的所有数据,但是当我运行它时,我只得到一次迭代,然后退出循环。我需要它运行直到它到达文件的末尾。

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

2 回答 2

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

}
return 0;

我还没有看到你的文件结构,但我猜这个代码片段会起作用。

于 2013-03-25T23:46:54.453 回答
0

你正在做的:

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

并且您的程序会在最里面的 while 循环中获取它可以获取的所有数字,从而弄乱您的数字-字符串-数字-数字序列。

当第二次检查第一个 while 时,它​​找不到一个数字,因为最里面的循环已经获取了每个数字,直到第一个字符串并退出。

使用 while()s 是一个不好的选择,尝试按照 spin_eight 的建议解析文件。

于 2013-03-25T23:59:12.727 回答