首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >c++从字符串解析整型

c++从字符串解析整型
EN

Stack Overflow用户
提问于 2010-12-15 02:18:28
回答 5查看 221.5K关注 0票数 90

可能重复:

How to parse a string to an int in C++?

我做了一些研究,一些人说使用atio,另一些人说它很糟糕,我无论如何都不能让它工作。

所以我只想直截了当地问,把字符串转换成整型的正确方法是什么。

代码语言:javascript
复制
string s = "10";
int i = s....?

谢谢!

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-12-15 02:20:01

std::string s= "10";int i= std::stoi(s);

请注意,如果无法执行转换,std::stoi将抛出std::invalid_argument类型的异常,或者如果转换导致溢出(即字符串值对于int类型太大),则抛出std::out_of_range异常。您可以使用std::stolstd:stoll,以防int对于输入字符串而言太小。

  • 在C++03/98中,可以使用以下任何选项:

std::string s= " 10 ";int i;//接近一个std::istringstream >> i;//这之后//接近两个sscanf(s.c_str(),"%d",&i);//这个之后,i是10

请注意,对于输入s = "10jh",上述两种方法将失败。它们将返回10,而不是通知错误。因此,安全和健壮的方法是编写自己的函数来解析输入字符串,并验证每个字符以检查它是否是数字,然后进行相应的工作。这里有一个健壮的实现(虽然没有经过测试):

代码语言:javascript
复制
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的略微修改版本。

票数 109
EN

Stack Overflow用户

发布于 2010-12-15 02:23:07

您可以使用boost::lexical_cast

代码语言:javascript
复制
#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;
}
票数 14
EN

Stack Overflow用户

发布于 2010-12-15 02:27:19

没有“正确的方法”。如果您想要一个通用的(但不是最优的)解决方案,您可以使用boost::lexical cast

C++的一种常见解决方案是使用std::ostream<< operator。您可以使用stringstreamstringstream::str()方法来转换为字符串。

如果你真的需要一种快速的机制(记住20/80规则),你可以寻找一个“专用”的解决方案,比如C++ String Toolkit Library

诚挚的问候,

Marcin

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4442658

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档