如何从冒号分隔的文本文件中分配变量 C++

How to assign variables from colon-separated text file c++

我有一个 .txt 文件:

A:One:1:2:15.
B:Two:0:6:5.
C:Three:0:4:6.
D:Four:0:4:8.
E:Five:0:6:2.

我需要读取文件,并将 (:) 之间的每个值分配给适当的变量。

到目前为止,这是我的代码:

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

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

        string code;
        string partName;
        int minimum;
        int maximum;
        int complexity;

        getline(ss, code, ':');
        getline(ss, partName, ':');
        getline(ss, minimum, ':');
        getline(ss, maximum, ':');
        getline(ss, complexity, ':');
        cout << code << partName << minimum << maximum << complexity << "\n";
    }
}


return 0;
}

这是我得到的错误:

a1.cpp:27:13: error: no matching function for call to 'getline'
        getline(ss, minimum, ':');

a1.cpp:28:13: error: no matching function for call to 'getline'
        getline(ss, maximum, ':');

a1.cpp:29:13: error: no matching function for call to 'getline'
        getline(ss, complexity, ':');

我是 c++ 的新手,所以非常感谢任何帮助!

getline(ss, minimum, ':');

std::getline 的第二个参数始终是 std::stringminimum 不是 std::string。它是一个 int,这就是编译失败的原因。在 C++ 中调用函数时,所有参数类型必须正确或可转换(隐式或通过用户指定的转换运算符)为函数期望的参数类型。

你也需要把这个词提取成一个std::string,然后用std::stoi library function把一个std::string转换成一个integer。