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