如何将C++字符串转换为int?

kru*_*pan 46 c++ int parsing stdstring

可能重复:
如何在C++中将字符串解析为int?

如何将C++字符串转换为int?

假设您希望字符串中包含实际数字(例如,"1","345","38944").

另外,让我们假设你没有提升,你真的想用C++方式来做,而不是狡猾的旧C方式.

Ran*_*ku' 74

#include <sstream>

// st is input string
int result;
stringstream(st) >> result;
Run Code Online (Sandbox Code Playgroud)

  • 然后检查错误:(stringstream(st)>> result)?cout <<结果:cerr <<"你输了"; (20认同)
  • 如果有错误怎么办?假设字符串中没有数字("hello!"而不是"5"). (3认同)

Mar*_*ork 33

使用C++流.

std::string       plop("123");
std::stringstream str(plop);
int x;

str >> x;

/* Lets not forget to error checking */
if (!str)
{
     // The conversion failed.
     // Need to do something here.
     // Maybe throw an exception
}
Run Code Online (Sandbox Code Playgroud)

PS.这个基本原理是boost库的lexical_cast<>工作原理.

我最喜欢的方法是提升 lexical_cast<>

#include <boost/lexical_cast.hpp>

int x = boost::lexical_cast<int>("123");
Run Code Online (Sandbox Code Playgroud)

它提供了一种在字符串和数字格式之间进行转换的方法.在它下面使用一个字符串流,所以任何可以编组成流然后从流中解组的东西(看看>>和<<运算符).

  • 否.如果流操作符无法从str中提取数字,则设置坏位.在布尔上下文中使用它(如上所述)将通过返回可转换为bool的对象来测试流是否正常.如果我测试'x',那么如果'x'中的值为0,它将失败.如果流未能提取任何内容,则'x'的值未定义. (5认同)