You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++新手求助:如何根据用户输入的商品项查找对应价格?

商品价格查找的C++实现方案

你的代码里存在几个明显问题:

  • 全局声明ifstream file("Item.txt")后,又在main里重复调用file.open,会导致文件打开错误,且fstream::ate是定位到文件末尾,完全不适合读取内容
  • findItem是未定义的变量,C++里没有这个默认对象
  • file.begin()/file.end()不是这样用的,文件流不能直接这么调用查找方法
  • cin >> product会在空格处停止读取,你的商品项(比如Item 1)包含空格,只能读到Item,无法获取完整商品名

推荐实现:用Map存储键值对(高效查找)

我们可以把文件中的商品名和价格对应存储到std::map里,这是最适合键值对查找的方案,步骤如下:

完整代码

#include <iostream>
#include <fstream>
#include <string>
#include <map>

using namespace std;

int main() {
    // 用map存储商品名-价格的键值对
    map<string, string> priceMap;
    ifstream file("Item.txt");
    string line;

    // 逐行读取文件,拆分商品和价格
    while (getline(file, line)) {
        // 找到$的位置,以此拆分商品名和价格
        size_t dollarPos = line.find('$');
        if (dollarPos != string::npos) {
            // 提取商品名并去除末尾多余空格
            string item = line.substr(0, dollarPos);
            item.erase(item.find_last_not_of(" \t") + 1);
            // 提取价格部分
            string price = line.substr(dollarPos);
            priceMap[item] = price;
        }
    }
    file.close();

    // 接收用户输入的完整商品名(包含空格)
    cout << "Enter item you want: ";
    string product;
    cin.ignore(); // 清除之前输入残留的换行符
    getline(cin, product);

    // 查找并输出结果
    auto it = priceMap.find(product);
    if (it != priceMap.end()) {
        cout << "Price: " << it->second << endl;
    } else {
        cout << "Item not found!" << endl;
    }

    return 0;
}

代码解释

  • std::map:自带有序存储和快速查找特性,比遍历数组效率高得多
  • getline(file, line):完整读取每一行内容,解决了商品名含空格的问题
  • line.find('$'):精准定位价格的起始位置,拆分商品名和价格
  • item.erase(...):去除商品名末尾的多余空格,确保用户输入的Item 1能匹配文件里的Item 1
  • cin.ignore():必须加这一行,否则getline会直接读取之前输入留下的换行符,导致获取不到用户输入的内容

备选实现:用数组+查找算法(适合理解基础遍历)

如果你想基于数组实现,可以用vector<pair<string, string>>存储,再用std::find_if算法查找:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<pair<string, string>> items;
    ifstream file("Item.txt");
    string line;

    while (getline(file, line)) {
        size_t dollarPos = line.find('$');
        if (dollarPos != string::npos) {
            string item = line.substr(0, dollarPos);
            item.erase(item.find_last_not_of(" \t") + 1);
            string price = line.substr(dollarPos);
            items.emplace_back(item, price);
        }
    }
    file.close();

    cout << "Enter item you want: ";
    string product;
    cin.ignore();
    getline(cin, product);

    // 用lambda表达式作为判断条件,遍历数组查找匹配项
    auto it = find_if(items.begin(), items.end(), [&product](const pair<string, string>& p) {
        return p.first == product;
    });

    if (it != items.end()) {
        cout << "Price: " << it->second << endl;
    } else {
        cout << "Item not found!" << endl;
    }

    return 0;
}

这种方式需要遍历整个数组,数据量大时查找速度不如map,但适合新手理解基础的遍历和查找逻辑。

内容的提问来源于stack exchange,提问作者Nathan_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 04:05:19