c++ - c++中字符串转整数问题

标签 c++

我遇到了一个问题

 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/

相关文章:

c++ - 丰富的编辑控件 : difference between rcPage and rc members of FORMATRANGE structure

c++ - 对重复代码使用宏是否可以接受?

c++ - 如何从 std::atomic<T> 中提取指针 T?

c++ - 模板函数指针作为模板参数

c++ - #define 导致 "Access violation reading location"

c++ - 如何禁用 C++ 7.1 名称修改? :(

c++ - 将 boost::make_recursive_variant 与元组一起使用

c++ - 如何实现引用构造函数?

c++ - 函数签名末尾的 && 是什么意思(在右括号之后)?

c++ - 无法使用 HTTPS 访问 gSOAP Web 服务