【发布时间】:2020-03-24 19:30:24
【问题描述】:
我正在尝试解决这个任务:
编写一个程序来读取名为 price.txt 的文件,该文件包含任意数量的产品名称和价格行,以美元 ($) 分隔。阅读产品后,您的程序必须分析所有产品并打印有关价格的统计信息 - 有多少产品的价格在范围内 - (0, 10], (10, 20] 和 20 以上。文本文件可以包含:
可口可乐$1.45
红酒$20.3
威士忌$100
水$1.2程序的一个示例输出,对于上面的输入,如下图:
0-10:2 个产品
10-20: 0 产品
20 岁以上:2 个产品
这段代码是我所了解的:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream ins; // declare an input file stream object
ins.open("prices.txt"); // open the file
if (ins.fail()) { // check if there was an error
cout << "Error opening file";
return -1;
}
int count1 = 0; //variable to count how many prices are from 0 - 10
int count2 = 0; //variable to count how many prices are from 10 - 20
int count3 = 0; //variable to count how many prices are above 20
string product;
float price = 0;
getline(ins, product, '$');
while (!ins.eof()) {
ins >> product >> price;
if (price > 0 && price <= 10.0) {
count1++;
}
else if (price > 10.0 && price <= 20.0) {
count2++;
}
else {
count3++;
}
ins.ignore(100, '\n'); // ignore the next newline
getline(ins, product, '$'); // read the product name until the $ sign
}
ins.close(); // close the file
cout << "0-10: " << count1 << " product(s) " << endl;
cout << "10-20: " << count2 << " product(s) " << endl;
cout << "above 20: " << count3 << " product(s) " << endl;
return 0;
}
【问题讨论】:
-
while(feof)is always wrong。只需while (ins >> product >> price) { -
Red Wine$20.3会因为空格而出人意料地抵抗ins >> product >> price。您将需要getline。使用美元符号作为分隔符