Page 1 of 3 123 LastLast
Results 1 to 10 of 21

Thread: Convert C++ String to Integer

  1. #1

    Convert C++ String to Integer

    What would be the best way to convert a standard C++ string into an integer

  2. #2
    Join Date
    Jun 2006
    Location
    Germany
    Beans
    16
    Distro
    Kubuntu Karmic Koala (testing)

    Re: Convert C++ String to Integer

    You mean something like string a[]="64000" into b = 64000?
    its as simple as that:
    b = atoi(a);

  3. #3
    Join Date
    Oct 2006
    Location
    Austin, Texas
    Beans
    2,712
    Distro
    Ubuntu 7.10 Gutsy Gibbon

    Re: Convert C++ String to Integer

    Well, with a C++ string, it should be converted to a C string first. This is easy...

    integer = atoi( my_string.c_str() );

  4. #4
    Join Date
    Jan 2006
    Beans
    961

    Re: Convert C++ String to Integer

    use stringstream for this stuff:

    Code:
    #include <iostream>
    #include <sstream>
    
    int main()
    {
      using namespace std;
    
      string s = "1234";
      stringstream ss(s); // Could of course also have done ss("1234") directly.
      
      int i;
      ss >> i;
      cout << i << endl;
      
      return 0;
    }

  5. #5
    Join Date
    Oct 2006
    Location
    Austin, Texas
    Beans
    2,712
    Distro
    Ubuntu 7.10 Gutsy Gibbon

    Re: Convert C++ String to Integer

    lnostdal is correct. "atoi" is more of the C way of doing it (which is why we have to convert it to a C style string), while lnostdals way is much more C++ esque. But either way will work.

  6. #6
    Join Date
    Jul 2005
    Beans
    1,535
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: Convert C++ String to Integer

    Actually, you shouldn't use atoi, not even in C. The problem is that if atoi fails, it returns a 0. But, if you are converting 0, you also get 0! Therefore, error detection becomes impossible. In C you should use sscanf. For example

    Code:
    #include <stdio.h>
    
    int main()
    {
      const char* s = "1234";
      int i = 0;
      
      if(sscanf(s, "%d", &i) == EOF)
      {
         //error
      }
      
      return 0;
    }
    Now you can detect if a failure occurred. If you want to convert it to a different format, all you have to do is change the format specifier. For example, to convert to a double you change "%d" to "%lf". Be careful that the variable type you want to convert it to matches the format specifier, good ol C doesn't bother to check stuff like that

    In C++ you use string streams because
    1) you can detect conversion failures. lnostdal didn't check in his example, so hopefully he won't mind me adding to his

    Code:
    #include <iostream>
    #include <sstream>
    
    int main()
    {
      using namespace std;
    
      string s = "1234";
      stringstream ss(s); // Could of course also have done ss("1234") directly.
      
      int i;
      
      if( (ss >> i).fail() )
      {
         //error
      }
      
      cout << i << endl;
      
      return 0;
    }
    2) Using string streams is type safe. Don't get that with the C way.
    Last edited by hod139; March 29th, 2007 at 08:57 PM.
    When I invented the Web, I didn't have to ask anyone's permission.
    ~Tim Berners-Lee on Net Neutrality
    -------------------------------------
    Visit the Ubuntu Programming IRC-channel at #ubuntu-programming (chat.freenode.net).

  7. #7
    Join Date
    Mar 2005
    Location
    Dunedin, NZ
    Beans
    559
    Distro
    Kubuntu 7.10 Gutsy Gibbon

    Re: Convert C++ String to Integer

    Personally these days I use boost::lexical_cast.

    Code:
    #include <boost/lexcal_cast.hpp>
    
    // ...
    int i = 42;
    std::string s = boost::lexical_cast<std::string>(i);
    int j = boost::lexical_cast<int>(s)
    ACCU - for programmers who care

  8. #8
    Join Date
    Oct 2006
    Beans
    62

    Re: Convert C++ String to Integer

    Code:
    #include <iostream>
    #include <limits>
    
    using namespace std;
    
    int main ( int argc, char* argv[] )
    {
       int i;
       cout << "enter an interger (or some random garbage): ";
       cout.flush();
       while ( (cin >> i).fail() )
       {
          // clear the error flag in the cin object
          cin.clear();
          // discard the erroneous user input
          cin.ignore(numeric_limits<streamsize>::max(), '\n');
          cout << "ooops! please try again: ";
          cout.flush();
       }
       cout << "thank you for entering " << i << endl;
    }
    This technique should be applicable to other stream objects and other non-integer types.

    http://www.cplusplus.com/reference/i.../ios/fail.html
    http://www.cplusplus.com/reference/i...ios/clear.html
    http://www.cplusplus.com/reference/i...am/ignore.html
    http://www.cplusplus.com/reference/i...treamsize.html
    http://publib.boulder.ibm.com/infoce...der_limits.htm
    Last edited by nadamsieee; September 24th, 2007 at 04:01 PM.

  9. #9
    Join Date
    Oct 2005
    Location
    UK
    Beans
    242

    Re: Convert C++ String to Integer

    Could use strtol function.

    long int strtol (const char *restrict STRING, char **restrict TAILPTR, int BASE)

    It uses TAILPTR to indicate the end of the value. This is much better than using the return value.

  10. #10
    Join Date
    May 2007
    Location
    Paris, France
    Beans
    927
    Distro
    Kubuntu 7.04 Feisty Fawn

    Re: Convert C++ String to Integer

    Quote Originally Posted by public_void View Post
    Could use strtol function.
    Again, that's plain old C.

    As noted previously, boost::lexical_cast is a very good C++ solution (the cleanest IMHO), unless for some reason you don't want to use boost in which case std::stringstream is the way to go.

    The big advantage of boost::lexical_cast is that it throws an exception on error, no need to add clutter for error checking.
    Last edited by aks44; September 24th, 2007 at 09:49 PM.
    Not even tinfoil can save us now...

Page 1 of 3 123 LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •