C++程序无法正确显示文本文件中的内容
C++ program not displaying the content from the text file correctly
我正在编写的程序是假设列出每个学生的所有付款,显示已支付和未付的金额。
但是,问题是由于我似乎找不到的某种原因,它无法正确显示。
付款.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 $5012 25 $752321 12 $884543 2323 $-2223
你能帮忙解释一下为什么这样做吗?谢谢
代码的关键部分在这里。
while (infile >> StudentCode >> Amount)
{
amountsPaid[StudentCode] += Amount;
}
此循环拉取数字对。这些是从流中拉出的对:
11 5012 254543 23232321 12
此时遇到文本Barclays
,因此 while 循环终止。那是因为文本无法转换为float
。
要解决您的问题,您需要切换到面向生产线的处理。使用getline()
一次拉出一条线。然后将行分解为不同的项目。一种可能的解决方案是这样的:
string line;
while (getline(infile, line))
{
istringstream strm(line);
strm >> StudentCode >> Amount;
amountsPaid[StudentCode] += Amount;
}
您的文件包含的内容实际上超过两列,而您只读取两列,因此下一个文件>>学生代码>>金额会将付款类型读取为学生代码。您应该在文件中只创建两列或丢弃更多列直到行尾,然后再阅读下一个"学生代码>>金额"组合,例如
而(提交>>学生代码>>金额)
{ 金额已付[学生代码] += 金额;
infile.getline(buff, size);它将读取剩余行
}
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何使用 c++ 实现并发文件/文本编辑?
- 我需要转换一些代码,以便它适用于输入和输出文件文本
- 通过套接字发送二进制文件.文本文件有效,其他文件无效
- 将大型数据文件拆分为多个小文件(文本格式)
- 如何读取输入文件(文本文件)并将输入验证为有效整数
- 从文本文件/文本流中读取Q字符串错误
- 从文本文件(文本解析器)C++中读取行和列的逻辑
- 如何将*.css文件(文本文件)的内容与附加信息存储在新文件中?
- 关于内存映射文件和使用大文件文本编辑器
- 如何在读取文件文本时跳过"n"
- 使用libzip从.zip获取文件(文本除外)