2013-03-30 74 views
-5

我正在爲學生編寫計算學費的課程。我得到一個無限循環,似乎無法找到原因?無法找到無限循環的原因

代碼:

#include <iostream> 
#include <string> 
#include <fstream> 
#include <iomanip> 

using namespace std; 

int main() 
{ 
    string ssn; 
    char resident; 
    int count = 0, hours; 
    double feesOther = 30, feesTech = 18, tuition, totalFees, sumTuition = 0, subTuition; 

    ofstream printFile ("StudentGrades.txt"); 
    if (!printFile) 
    { 
     cout << " Error opening printFile" << endl; 
     system ("pause"); 
     return 100; 
    } 

    ifstream studentFile; 
    studentFile.open("c:\\lab5b.dat"); 

    if (!studentFile) 
    { 
     cout << "Open error on lab5a.dat" << endl; 
     system ("pause"); 
     return 101; 
    } 

    studentFile >> ssn >> resident >> hours; 

    cout << "SSN   Tuition\n"; 
    cout << "--------------------\n"; 

    while (!studentFile.eof()) 
    { 
     if (resident == 'Y' || resident == 'y') 
     { 
      if (hours >= 12) 
       tuition = 1548; 

      else 

       tuition = hours * 129; 
     } 
     if (resident == 'N' || resident == 'n') 
     { 
      if (hours >= 12) 
       tuition = 6360; 

      else 

       tuition = hours * 530; 
     } 

     totalFees = feesOther + (hours * feesTech); 

     if (totalFees > 112.50) 
      totalFees = feesOther + 112.50; 

     subTuition = tuition + totalFees; 
     sumTuition += tuition ; 
     count++; 


     cout << ssn << setw(7) << showpoint << setprecision(2) << subTuition << endl; 
     cout << "Total Semester Tuition: " << sumTuition << endl; 

     studentFile >> ssn >> subTuition; 


    } 

    studentFile.close();  
    printFile.close();  

    system ("pause"); 
} 
+9

要求人們發現代碼中的錯誤並不是特別有效。您應該使用調試器(或者添加打印語句)來分析問題,追蹤程序的進度,並將其與預期發生的情況進行比較。只要兩者發生分歧,那麼你就發現了你的問題。 (然後,如果有必要,您應該構建一個[最小測試用例](http://sscce.org)。) –

+0

無限循環?循環在哪裏?循環的條件是什麼?循環變量'!studentFile.eof()'的含義是什麼? – CppLearner

+0

試着參考這個。 http://stackoverflow.com/questions/1494342/end-of-file-in-c – wmfairuz

回答

1

studentfile是最有可能發生了失效時,因爲你永遠檢查讀操作是否成功與否。更改代碼如下:

if(!(studentFile >> ssn >> resident >> hours)) 
{ 
    std::cout << "read failed"; 
    return 1; 
} 

//...  

do 
{ 
    // Do stuff 
    // REMOVE THIS LINE: studentFile >> ssn >> subTuition; 
} while (studentFile >> ssn >> subTuition); // while loop stops as soon as read fails 

的關鍵教訓,在這裏學到的是總是讀期間執行錯誤校驗,和寫入操作。 另外,請閱讀Why is iostream::eof inside a loop condition considered wrong?,因爲while (!studentFile.eof())被認爲是C++反模式。