C++ 错误:无法转换';赋值中的std::string(又称std::basic_string<;char>;}';到';int';)
我有一个问题-我想将标准输入行中的值存储为int,但不确定如何转换为int:C++ 错误:无法转换';赋值中的std::string(又称std::basic_string<;char>;}';到';int';),c++,C++,我有一个问题-我想将标准输入行中的值存储为int,但不确定如何转换为int: string line; int value; getline(cin,line); istringstream ss(line); while (ss>>line) { if (ss.eof()==false) { // stores non ints in strings } else { value=line; //ERROR } }
string line;
int value;
getline(cin,line);
istringstream ss(line);
while (ss>>line) {
if (ss.eof()==false) {
// stores non ints in strings
}
else {
value=line; //ERROR
}
}
我曾尝试使用标准文档材料转换此内容,但我哪儿也不去。我做错了什么?您可以使用
std::stoi
:
value=std::stoi(line);
在检查
ss.fail()
时,可以使用istringstream
尝试将值加载到int中
当然,这可以根据您的需要进行一些修改。谢谢。我试过了,但我得到了一个错误:“stoi”不是“std”的成员。我已经包含了正确的库,例如std::stoi,那么这不是库的问题吗?@您包括的图书管理员,您使用的是c++11吗?不过可能有更干净的方法来做到这一点……只需执行
while(cin>>值)
通常是您想要的。
ss >> temp; // where temp is an int
if(ss.fail())
{
// handle the error because the value wasn't an int
}
else
{
// process your int
}