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

前端 未结 17 1737
忘了有多久
忘了有多久 2020-11-21 11:01

What\'s the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero).

相关标签:
17条回答
  • 2020-11-21 11:41

    You can use the a stringstream from the C++ standard libraray:

    stringstream ss(str);
    int x;
    ss >> x;
    
    if(ss) { // <-- error handling
      // use x
    } else {
      // not a number
    }
    

    The stream state will be set to fail if a non-digit is encountered when trying to read an integer.

    See Stream pitfalls for pitfalls of errorhandling and streams in C++.

    0 讨论(0)
  • 2020-11-21 11:44

    From C++17 onwards you can use std::from_chars from the <charconv> header as documented here.

    For example:

    #include <iostream>
    #include <charconv>
    #include <array>
    
    int main()
    {
        char const * str = "42";
        int value = 0;
    
        std::from_chars_result result = std::from_chars(std::begin(str), std::end(str), value);
    
        if(result.error == std::errc::invalid_argument)
        {
          std::cout << "Error, invalid format";
        }
        else if(result.error == std::errc::result_out_of_range)
        {
          std::cout << "Error, value too big for int range";
        }
        else
        {
          std::cout << "Success: " << result;
        }
    }
    

    As a bonus, it can also handle other bases, like hexadecimal.

    0 讨论(0)
  • 2020-11-21 11:45

    In C, you can use int atoi (const char * str),

    Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.

    0 讨论(0)
  • 2020-11-21 11:49

    You can use stringstream's

    int str2int (const string &str) {
      stringstream ss(str);
      int num;
      ss >> num;
      return num;
    }
    
    0 讨论(0)
  • 2020-11-21 11:51

    This is a safer C way than atoi()

    const char* str = "123";
    int i;
    
    if(sscanf(str, "%d", &i)  == EOF )
    {
       /* error */
    }
    

    C++ with standard library stringstream: (thanks CMS )

    int str2int (const string &str) {
      stringstream ss(str);
      int num;
      if((ss >> num).fail())
      { 
          //ERROR 
      }
      return num;
    }
    

    With boost library: (thanks jk)

    #include <boost/lexical_cast.hpp>
    #include <string>
    
    try
    {
        std::string str = "123";
        int number = boost::lexical_cast< int >( str );
    }
    catch( const boost::bad_lexical_cast & )
    {
        // Error
    }
    

    Edit: Fixed the stringstream version so that it handles errors. (thanks to CMS's and jk's comment on original post)

    0 讨论(0)
  • 2020-11-21 11:52

    You could use this defined method.

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

    And if you were to convert from String to an Integer, you would just do the following.

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

    The output would be 102.

    0 讨论(0)
提交回复
热议问题