【问题标题】:Using std::ifstream to read prices of products from a file使用 std::ifstream 从文件中读取产品价格
【发布时间】: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 &gt;&gt; product &gt;&gt; price) {
  • Red Wine$20.3 会因为空格而出人意料地抵抗ins &gt;&gt; product &gt;&gt; price。您将需要getline。使用美元符号作为分隔符

标签: c++ fstream ifstream


【解决方案1】:

@cigien @user4581301 谢谢你们的反馈真的很感激,但我有点自己修复它,因为我正在阅读产品,直到在 while 循环之前带有getline(ins, product, '$'); 的 $-sign 并且光标已经在价格但ins &gt;&gt; product &gt;&gt; price; 之后我将产品的价格放在产品上,因为我阅读了两次产品。只需删除ins &gt;&gt; product &gt;&gt; price 的产品,使其成为ins &gt;&gt; price 即可解决所有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 2015-11-05
    • 2010-12-09
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多