2013-03-25 51 views
0

這是我到目前爲止的代碼。我從輸入文件中獲取數據。該文件包含我調用的每個變量所需的所有數據,但是當我運行它時,我只獲得一次迭代,然後退出循環。我需要它運行,直到它到達文件的末尾。爲什麼在第一次迭代後C++ io流的循環會中斷?

#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

我征服你找到一個更具描述性的標題你的問題...大多數人在這裏(包括我)問問題關於我們自己的錯誤或碰撞。 – Barranka 2013-03-25 22:23:02

+0

用cout <<「Here」:)開始調試 – 2013-03-25 22:25:13

+0

我建議您將您正在使用的編程語言添加到標籤中。通過進入帖子,我可以清楚地看到它是C++,但是我認爲如果你添加它,你可以得到更多的結果並以更快的方式。 – 2013-03-25 22:27:53

回答

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; 

我haven`t見過你的文件結構,但我客串此代碼段將工作。

+0

謝謝我最終做了這樣的事情,但使用while(pTemp >> pnumber),而不是cin.good,它似乎工作相同。非常感謝。 – 2013-03-26 01:03:14

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()s是一個不錯的選擇,嘗試將文件解析爲spin_eight的建議。

+0

啊,非常感謝,我幫了我很多。 – 2013-03-26 01:00:35

相關問題