转换一个没有。从字符串到整数。例如:str:“1234” convert to int a = 1234;
我想与适当的交代提示
转换一个没有。从字符串到整数。例如:str:“1234” convert to int a = 1234;
我想与适当的交代提示
使用atoi()
:
int foo = atoi(str.c_str());
我想要不使用内置函数的答案 – Raja 2011-03-13 13:42:42
您没有说明。 – 2011-03-13 14:09:10
如果您想正确执行此操作并测试转换中的错误,我建议使用boost::lexical_cast。下面是使用的例子:
#include <boost/lexical_cast>
std::string num_string("1234");
try
{
int num=boost::lexical_cast<int>(numString);
}
catch (boost::bad_lexical_cast &ex)
{
// Handle failed conversions
}
如果因任何原因,你不能在项目中使用升压,至少使用一个标准stringstream
进行转换,以获得错误校验一些外表。
AFAIR lexical_cast非常昂贵。尽管同意使用stringstream – Ralf 2011-03-13 13:46:12
既然你标记它的C++,你可以看看istringstream
:
bool convertStr(const char *str, unsigned int *num) {
istringstream iss(str);
return (iss >> *num);
}
或者你甚至可以使用模板:
template <class T>
bool fromString(T &t, const string &s,
ios_base& (*f)(ios_base&) = dec) {
istringstream iss(s);
return !(iss >> f >> t).fail();
}
复制http://stackoverflow.com/questions/3858978/ convert-string-to-integer-in-c – k107 2011-03-13 13:36:39