我遇到了一个问题
string ccc="example";
int cc=atoi(csession);
它说不能将参数“1”的“std::string”转换为“const char*”到“int atoi(const char*)”
我应该将字符串转换为 char 数组然后应用于 atoi
还是有任何其他方式
最佳答案
istringstream in(ccc);
int cc;
in >> cc;
if(in.fail())
{
// error, ccc had invalid format, more precisely, ccc didn't begin with a number
//throw, or exit, or whatever
}
istringstream
在标题中 <sstream>
在namespace std
.上面的代码将从字符串中提取第一个整数,即如果 ccc
是“123ac”cc
将是 123。如果 ccc
然后是“abc123”cc
将具有未定义的值和 in.fail()
会是真的。
关于c++ - c++中字符串转整数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3899839/