필자가 작성한 프로그램은 각 학생이 지불 한 모든 지불액을 나열하고 지급액과 미 지불 금액을 표시하는 것으로 가정합니다.C++ 프로그램이 텍스트 파일의 내용을 올바르게 표시하지 않습니다.
그러나 문제는 내가 찾지 못하는 어떤 이유로 올바르게 표시되지 않는다는 것입니다.
는다음과 같은 순서로 payment.txt 파일 내용 :
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
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
지금까지 코드 (빈 현금 수단) 대신에 다음을 실행하십시오 :
11 50 $ 012 12 25 $2321 12 $ 88 454 3 2323 $ -2223
왜 이렇게하고 있는지 설명해 주시겠습니까? 감사합니다.
남아 읽어 줄 테니 간단한 수정 ('N \'표준 : : numeric_limits <표준 : streamsize> :: 최대())'infile.ignore를 넣어하는 것입니다;' 'while' 루프 안에 있습니다. – jrok
@jrok 그 이유를 설명해야합니다. –
파일의 일부 줄에는 분명히 읽고 싶지 않은 데이터가 들어 있습니다. 자동으로 나가는 것은 아니기 때문에, 이전 주석의 문장은 스트림이 최대 스트림 크기 또는 첫 번째 줄 바꿈 문자까지 모두를 무시하도록 알려줍니다. @DavidHeffernan은 그의 대답에 대체 접근법을 제공합니다 (가능한 오류를 확인하고 처리하기가 쉽기 때문에 IMO). – jrok