C ++程序无法正确显示文本文件中的内容

时间:2012-12-13 20:25:50

标签: c++ visual-studio-2010 visual-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 4543 2323 $ -2223

你能帮忙解释一下为什么这样做吗? 感谢

2 个答案:

答案 0 :(得分: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 :(得分:1)

您的文件包含的内容实际上超过两列,而您只读取两列,因此下一页 infile&gt;&gt; StudentCode&gt;&gt;金额将读取付款类型为StudentCode。您应该在文件中只创建两列,或者在读取下一个“StudentCode&gt;&gt; Amount”组合之前丢弃更多列直到行结束,例如
while(infile&gt;&gt; StudentCode&gt;&gt; Amount)
{
amountPaid [StudentCode] + =金额;
infile.getline(buff,size); //它会读剩余的线
}