可能重复:
How to parse a string to an int in C++?
我做了一些研究,一些人说使用atio,另一些人说它很糟糕,我无论如何都不能让它工作。
所以我只想直截了当地问,把字符串转换成整型的正确方法是什么。
string s = "10";
int i = s....?
谢谢!
发布于 2010-12-15 02:20:01
std::stoi
作为:std::string s= "10";int i= std::stoi(s);
请注意,如果无法执行转换,std::stoi
将抛出std::invalid_argument
类型的异常,或者如果转换导致溢出(即字符串值对于int
类型太大),则抛出std::out_of_range
异常。您可以使用std::stol
或std:stoll
,以防int
对于输入字符串而言太小。
std::string s= " 10 ";int i;//接近一个std::istringstream >> i;//这之后//接近两个sscanf(s.c_str(),"%d",&i);//这个之后,i是10
请注意,对于输入s = "10jh"
,上述两种方法将失败。它们将返回10,而不是通知错误。因此,安全和健壮的方法是编写自己的函数来解析输入字符串,并验证每个字符以检查它是否是数字,然后进行相应的工作。这里有一个健壮的实现(虽然没有经过测试):
int to_int(char const *s)
{
if ( s == NULL || *s == '\0' )
throw std::invalid_argument("null or empty string argument");
bool negate = (s[0] == '-');
if ( *s == '+' || *s == '-' )
++s;
if ( *s == '\0')
throw std::invalid_argument("sign character only.");
int result = 0;
while(*s)
{
if ( *s < '0' || *s > '9' )
throw std::invalid_argument("invalid input string");
result = result * 10 - (*s - '0'); //assume negative number
++s;
}
return negate ? result : -result; //-result is positive!
}
此解决方案是my another solution的略微修改版本。
发布于 2010-12-15 02:23:07
您可以使用boost::lexical_cast
#include <iostream>
#include <boost/lexical_cast.hpp>
int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;
try {
i = boost::lexical_cast<int>( s1 );
}
catch( boost::bad_lexical_cast & e ){
std::cout << "Exception caught : " << e.what() << std::endl;
}
try {
i = boost::lexical_cast<int>( s2 );
}
catch( boost::bad_lexical_cast & e ){
std::cout << "Exception caught : " << e.what() << std::endl;
}
return 0;
}
发布于 2010-12-15 02:27:19
没有“正确的方法”。如果您想要一个通用的(但不是最优的)解决方案,您可以使用boost::lexical cast
。
C++的一种常见解决方案是使用std::ostream
和<< operator
。您可以使用stringstream
和stringstream::str()
方法来转换为字符串。
如果你真的需要一种快速的机制(记住20/80规则),你可以寻找一个“专用”的解决方案,比如C++ String Toolkit Library
诚挚的问候,
Marcin
https://stackoverflow.com/questions/4442658
复制相似问题