本文介绍了c ++从字符串解析int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一些研究,有些人说使用atio,别人说这是坏的,我不能让它工作。

I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.

所以我只想问一下,把字符串转换为int的正确方法。

So I just want to ask flat out, whats the right way to convert a string to a int.

string s = "10";
int i = s....?


$ b

谢谢!

Thanks!

推荐答案


  • 在C ++ 11中,使用为:

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

    请注意, std :: stoi 例如 std :: invalid_argument 如果无法执行转换,或 std :: out_of_range 溢出(即当字符串值对于 int 类型太大时)。您可以使用或 int 对于输入字符串似乎过小。

    Note that std::stoi will throw exception of type std::invalid_argument if the conversion cannot be performed, or std::out_of_range if the conversion results in overflow(i.e when the string value is too big for int type). You can use std::stol or std:stoll though in case int seems too small for the input string.

    在C ++ 03/98中,可以使用以下命令:

    In C++03/98, any of the following can be used:

    std::string s = "10";
    int i;
    
    //approach one
    std::istringstream(s) >> i; //i is 10 after this
    
    //approach two
    sscanf(s.c_str(), "%d", &i); //i is 10 after this
    


  • 上述两种方法对于输入 s =10jh将失败。它们将返回10而不是通知错误。所以安全可靠的方法是编写自己的函数来解析输入字符串,并验证每个字符以检查它是否是数字,然后相应地工作。这里是一个强大的实现(未经测试):

    Note that the above two approaches would fail for input s = "10jh". They will return 10 instead of notifying error. So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. Here is one robust implemtation (untested though):

    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' )
              {
                  result = result * 10  - (*s - '0');  //assume negative number
              }
              else
                  throw std::invalid_argument("invalid input string");
              ++s;
         }
         return negate ? result : -result; //-result is positive!
    } 
    

    此解决方案是。

    这篇关于c ++从字符串解析int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:48