c++用什么方法把字符串(char *)解析成int?健壮和清晰的错误处理是一个加分项(而不是返回零)。


当前回答

您可以使用这个已定义的方法。

#define toInt(x) {atoi(x.c_str())};

如果要将String转换为Integer,只需执行以下操作。

int main()
{
string test = "46", test2 = "56";
int a = toInt(test);
int b = toInt(test2);
cout<<a+b<<endl;
}

输出是102。

其他回答

您可以使用Boost的lexical_cast,它将此包装在一个更通用的接口中。 lexical_cast<目标>(源)失败时抛出bad_lexical_cast。

你可以使用stringstream的

int str2int (const string &str) {
  stringstream ss(str);
  int num;
  ss >> num;
  return num;
}

您可以使用这个已定义的方法。

#define toInt(x) {atoi(x.c_str())};

如果要将String转换为Integer,只需执行以下操作。

int main()
{
string test = "46", test2 = "56";
int a = toInt(test);
int b = toInt(test2);
cout<<a+b<<endl;
}

输出是102。

如果你有c++ 11,现在合适的解决方案是<string>中的c++整数转换函数:stoi, stol, stoul, stoll, stoull。当给出不正确的输入时,它们会抛出适当的异常,并在底层使用快速和小型的strto*函数。

如果您被c++的早期版本所困扰,那么在实现中模拟这些函数将是向前可移植的。

在C中,你可以使用int atoi (const char * str),

解析c字串str,将其内容解释为整数,该整数作为int类型的值返回。