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

C++借助tellg()查找文件指定商品信息输出到控制台失败如何解决

C++文件读取查询问题修复

代码无法正常运行的核心原因

  • 查询变量被覆盖:你预先用cin >> pro_name存储了用户输入的待查询产品名,但后续循环读取文件内容时直接复用了同一个pro_name变量存储读取结果,导致原始查询值被覆盖,逻辑上只能固定匹配硬编码的"maaza",无法响应用户输入的其他查询词。
  • eof()使用错误:while(!file.eof())的判断逻辑存在缺陷,eof标识只有在读取完文件最后一个内容后才会触发,会导致最后一次读取失败后仍执行一次循环逻辑,引发异常输出。
  • 硬编码偏移量不可靠:找到匹配项后你使用seekg(pos-4, ios::beg)回退指针,减4的偏移是硬编码的,受操作系统换行符格式(Windows为\r\n占2字节、Linux为\n占1字节)、行前空格数量影响,无法保证定位准确,大概率会读到错误位置。
  • 缺少文件打开校验:代码未判断文件是否打开成功,若文件不存在、路径错误或无读取权限,后续所有读取操作都会直接失败,无任何错误提示。

修复方案说明

  1. 拆分查询变量和临时读取变量,避免查询值被覆盖
  2. 将文件读取操作放到while判断条件中,修复eof判断问题
  3. 匹配到目标产品后直接输出后续对应信息,无需硬编码调整文件指针,避免定位错误
  4. 增加文件打开成功校验

修复后代码

#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;

int main(){
    fstream file;
    string filename = "stockk.txt";
    file.open(filename.c_str());
    // 增加文件打开校验
    if (!file.is_open()) {
        cout << "文件打开失败,请检查路径是否正确" << endl;
        return 1;
    }
    string target_name;
    cout << "Enter the product name you want to display : ";
    cin >> target_name;
    int flag = 0;
    string temp_str;
    while (file >> temp_str) {
        if (temp_str == target_name) {
            flag = 1;
            cout << "product name matched\n";
            // 直接输出当前匹配项所在行剩余内容+后续3组属性
            cout << "Name : " << target_name << endl;
            int attr_count = 3; // 剩余要输出的Cost、Price、Quantity共3组
            while (attr_count > 0 && file >> temp_str) {
                if (temp_str == "Name") break; // 读到下一个产品的开头就停止
                cout << temp_str << " ";
                // 每读到数字就是一组属性结束,换行
                if (isdigit(temp_str[0])) {
                    cout << endl;
                    attr_count--;
                }
            }
            break;
        }
    }
    
    if (flag == 0) {
        cout << "Go Home\n"; 
    }
    file.close();
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:00:03