我正在編寫的程序是假設列出每個學生所做的所有付款,顯示已付款和未付款。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
你能幫忙解釋爲什麼這樣做嗎? 謝謝
一個簡單的修正將是把'infile.ignore(的std :: numeric_limits <性病:: streamsize可> :: MAX(), '\ n');'在'while'循環中。 – jrok
@jrok你應該解釋爲什麼這是有效的。 –
文件中的某些行包含您顯然不想閱讀的數據。但它不會自動跳出你的方式,因此:我之前評論中的聲明告訴流忽略所有內容,直到最大流大小或第一個新行字符 - 無論它們遇到什麼。 @DavidHeffernan在他的回答中提供了另一種方法(更好的方法,因爲它更容易檢查和處理可能的錯誤,IMO)。 – jrok