2012-12-13 102 views
0

我正在編寫的程序是假設列出每個學生所做的所有付款,顯示已付款和未付款。C++程序不能正確顯示文本文件的內容

但問題是,由於某些原因,我無法正確顯示它。

按以下順序的payment.txt文件內容: 學生守則金額類型(空白意味着現金)

11 50 
12 25 4543 2323 2321 
12 25 Barclays 
13 100 
14 100 
15 50 4545 6343 4342 
15 25 HSBC 
16 100 
17 100 
18 100 
19 100 
20 25 4546 3432 3211 
21 75 
22 100 Lloyds 
23 100 

這裏是迄今爲止代碼:

void payment() 
{ 
    // Display message asking for the user input 
    std::cout << "\nList all payment made by each student, show amount paid and outstanding." << std::endl; 

    // Read from text file and Display list of payment 

    std::ifstream infile;    // enable to open, read in and close a text file 
    float StudentCode;     // to store the student enrolment number 
    float Amount;      // to store the amount of money 
    float Type;       // to store information on type of payment made 
    float Outstanding;     // to store amount of money is due 
    std::map<int, float> amountsPaid; 

    infile.open("Payment.txt");   // open a text file called Payment 

    if (!infile)     
    { 
     std::cout << "List is empty" << std::endl;  // if the file is empty it output the message 
    } 
    else 
    { 
     // Display Headings and sub-headings 
     std::cout << "\nList of Payment: " << std::endl; 
     std::cout << "" << std::endl; 
     std::cout << "Enrolment No." << " " << "Amount" << " " << "Outstanding" << std::endl; 

     // accumulate amounts 
     while (infile >> StudentCode >> Amount) 
     { 
      amountsPaid[StudentCode] += Amount; 
     } 

     // loop through map and print all entries 
     for (auto i = amountsPaid.begin(); i != amountsPaid.end(); ++i) 
     { 
      float outstanding = 100 - i->second; 
      // Display the list of payment made by each student 
      std::cout << i->first << "  " << i->second << " " << "$: " << outstanding << '\n' << std::endl; 
     } 
    } 

    infile.close();   // close the text file 
} 

它顯示下面是它的運行時間:

11 50 $ 50 12 25 $ 75 2321 12 $ 88 454 3 2323 $ -2223

你能幫忙解釋爲什麼這樣做嗎? 謝謝

+1

一個簡單的修正將是把'infile.ignore(的std :: numeric_limits <性病:: streamsize可> :: MAX(), '\ n');'在'while'循環中。 – jrok

+0

@jrok你應該解釋爲什麼這是有效的。 –

+1

文件中的某些行包含您顯然不想閱讀的數據。但它不會自動跳出你的方式,因此:我之前評論中的聲明告訴流忽略所有內容,直到最大流大小或第一個新行字符 - 無論它們遇到什麼。 @DavidHeffernan在他的回答中提供了另一種方法(更好的方法,因爲它更容易檢查和處理可能的錯誤,IMO)。 – jrok

回答

2

代碼的關鍵部分在這裏。

while (infile >> StudentCode >> Amount) 
{ 
    amountsPaid[StudentCode] += Amount; 
} 

此循環拉數對數。這些是被拉開流的對:

 
11 50 
12 25 
4543 2323 
2321 12 

在這一點上的文本Barclays遇到,因此while循環終止。這是因爲文字不能轉換成float

要解決您的問題,您需要切換到面向行的處理。使用getline()一次拉出一條線。然後將其分解成不同的項目。一個可能的解決辦法是,像這樣:

string line; 
while (getline(infile, line)) 
{ 
    istringstream strm(line); 
    strm >> StudentCode >> Amount; 
    amountsPaid[StudentCode] += Amount; 
} 
1

什麼文件包含實際上是兩個以上的列和你正在閱讀只有兩列,因此,未來INFILE >> StudentCode >>金額將讀取的類型作爲StudentCode付款。在閱讀下一個「學員代碼>>金額」組合之前,您應該只在文件中創建兩列或放棄更多列直到行尾。
而(infile中>> >> StudentCode量)
{
        amountsPaid [StudentCode] + =量;
        infile.getline(buff,size); //它會讀取剩餘線
}