![](/img/trans.png)
[英]How to read bytes from file using std::ifstream to std::array?
[英]Using std::ifstream to read prices of products from a file
我正在尝试解决这个任务:
编写一个程序来读取一个名为prices.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;
}
@cigien @user4581301 谢谢你们的反馈,真的很感激,但我自己修复了它,因为我正在阅读产品直到 $-sign with getline(ins, product, '$');
在 while 循环之前,光标已经在价格处,但带有ins >> product >> price;
之后我将产品的价格放在产品上,因为我阅读了两次产品。 只需删除ins >> product >> price
使其ins >> price
解决所有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.