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

前端 未结 17 1705
忘了有多久
忘了有多久 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: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 
    #include 
    
    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)

提交回复
热议问题