[英]How to assign variables from colon-separated text file c++
I have a.txt file:我有一个.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.
And I need to read the file, and assign each value between the (:) to an appropriate variable.我需要读取文件,并将 (:) 之间的每个值分配给适当的变量。
Here is my code so far:到目前为止,这是我的代码:
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;
}
Here are the errors I get:这是我得到的错误:
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, ':');
I'm quite new to c++ so any help would be greatly appreciated!我是 c++ 的新手,所以非常感谢您的帮助!
getline(ss, minimum, ':');
The second parameter to std::getline
is always a std::string
. std::getline
的第二个参数始终是std::string
。 minimum
is not a std::string
. minimum
不是std::string
。 It is an int
, this is why this fails to compile.它是一个
int
,这就是编译失败的原因。 When calling a function in C++ all parameter types must be correct, or convertible (implicitly or by a user-specified conversion operator) to the parameter types that the function expects.当在 C++ 中调用 function 时,所有参数类型必须正确,或可转换(隐式或通过用户指定的转换运算符)为 function 期望的参数类型。
You need to extract this word into a std::string
, too, then use the std::stoi
library function to convert a std::string
into an int
eger.您还需要将这个词提取到
std::string
中,然后使用std::stoi
库 function将std::string
转换为int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.