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

C++读取冒号分隔文本文件赋值变量 解决getline无匹配函数报错

报错原因

std::getline 函数的第二个参数只支持 std::string 类型,你传入的 minimum、maximum、complexity 都是int类型,没有匹配的函数重载,所以编译报错。

解决方法

你可以先把所有字段都先读到字符串变量中,再把数值类型的字段用std::stoi()函数转成int类型即可,修改后的完整代码如下:

// 先引入必要头文件
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    ifstream theFile("Parts.txt");

    if(theFile.is_open())
    {
        string line;
        while(getline(theFile, line))
        {
            stringstream ss(line);

            string code;
            string partName;
            // 声明临时字符串存储数值字段
            string min_str, max_str, comp_str;
            int minimum;
            int maximum;
            int complexity;

            getline(ss, code, ':');
            getline(ss, partName, ':');
            getline(ss, min_str, ':');
            getline(ss, max_str, ':');
            getline(ss, comp_str, ':');

            // 字符串转int类型
            minimum = stoi(min_str);
            maximum = stoi(max_str);
            // 你的示例文件每行最后一个值带小数点,转int前先去除末尾的点更严谨
            if (!comp_str.empty() && comp_str.back() == '.') {
                comp_str.pop_back();
            }
            complexity = stoi(comp_str);

            cout << code << " " << partName << " " << minimum << " " << maximum << " " << complexity << "\n";
        }
        theFile.close();
    }
    else {
        cout << "文件打开失败,请检查文件路径是否正确" << endl;
    }

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:51:02