2012-12-13 2 views
0

필자가 작성한 프로그램은 각 학생이 지불 한 모든 지불액을 나열하고 지급액과 미 지불 금액을 표시하는 것으로 가정합니다.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

왜 이렇게하고 있는지 설명해 주시겠습니까? 감사합니다.

+1

남아 읽어 줄 테니 간단한 수정 ('N \'표준 : : numeric_limits <표준 : streamsize> :: 최대())'infile.ignore를 넣어하는 것입니다;' 'while' 루프 안에 있습니다. – jrok

+0

@jrok 그 이유를 설명해야합니다. –

+1

파일의 일부 줄에는 분명히 읽고 싶지 않은 데이터가 들어 있습니다. 자동으로 나가는 것은 아니기 때문에, 이전 주석의 문장은 스트림이 최대 스트림 크기 또는 첫 번째 줄 바꿈 문자까지 모두를 무시하도록 알려줍니다. @DavidHeffernan은 그의 대답에 대체 접근법을 제공합니다 (가능한 오류를 확인하고 처리하기가 쉽기 때문에 IMO). – jrok

답변

2

코드의 주요 부분은 여기에 있습니다.

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

이 루프는 숫자 쌍을 가져옵니다. 텍스트 Barclays가 발생하고 있으므로 while 루프가 종료하는 시점에서

 
11 50 
12 25 
4543 2323 
2321 12 

: 다음은 스트림 뽑아 얻을 쌍입니다. 텍스트를 float으로 변환 할 수 없기 때문입니다.

문제를 해결하려면 줄 단위 처리로 전환해야합니다. 한 번에 한 줄씩 뽑아 내려면 getline()을 사용하십시오. 그리고 그 줄을 별개의 항목으로 나눕니다. 한 가지 가능한 솔루션과 같이 될 것이다 :

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

가 어떤 파일에 포함 된 것은 실제로 두 개 이상의 열이며, 당신은 단지 두 개의 열을 읽고, 그래서 다음 INFILE >> StudentCode >> 금액이 유형을 읽 학생 코드로 지불. 다음 "StudentCode >> Amount"조합을 읽기 전에 파일에 두 개의 열만 작성하거나 줄 끝까지 추가 열을 버려야합니다.
동안 (INFILE >> >> StudentCode 양)
{
        amountsPaid [StudentCode] + = 금액
        infile.getline (buff, size); //이 라인
}

관련 문제