Convert C++ string to int

This is a discussion on Convert C++ string to int within the C++ Programming forums, part of the General Programming Boards category; I am currently using the following code to convert a string (or part of it) into an integer: Code: string ...

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    38

    Convert C++ string to int

    I am currently using the following code to convert a string (or part of it) into an integer:

    Code:
    string myString;
    
    ......
    
    int temp = 0;
    sscanf(myString.c_str(), "%d", &temp);
    This code will put the integer value into temp. It will also disregard any alpha characters after the int.
    I realise that this is a bit of a mix of C and C++. Is there a better way to do this in C++? Or do I need to convert it to a C string first??

    Thanks
    Mark

  2. #2
    Registered User
    Join Date
    Jan 2003
    Posts
    311
    Code:
    std::istringstream iss(myString);
    int n;
    if(iss >> n && iss.eof()) {
       // myString is a properly formated number with no trailing characters or whitespace
      // leading whitespace is ignored
    } else {
      iss.clear(); // allows us to work with the string again.
      iss.get(); // is the character that goofed things up.
      iss.tellg(); // is the position in the string of the offending character.
    }
    If you want to allow trailing whitespace, but not characters or more numbers or a floating
    point number you could use
    Code:
    if(iss >> n >> std::ws && iss.eof()) ...

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    20,968
    There's this entry in the FAQ
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    the easiest way to convert a std::string to int is STILL using the C atoi() function. Sometimes C is still the best -- even though atoi() does not check for integer overflow.

    Code:
    std::string str = "123";
    int n;
    n = atoi(str.c_str());
    Now isn't that a whole lot simpler than all that stringstream crap posted previously?
    Last edited by Ancient Dragon; 01-18-2006 at 09:42 AM.

  5. #5
    Super Moderater.
    Join Date
    Jan 2005
    Posts
    374
    Personally, I prefer the stringstream crap posted by laserlight in the FAQ.
    Last edited by treenef; 01-18-2006 at 02:58 PM.

  6. #6
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    what you want is boost::lexical_cast
    simple and elegant, but also typesafe and extensible.

    Code:
    std::string aString = "123";
    int val = boost::lexical_cast<int>(aString);
    The price you pay for this is a small decrease in performance, but if converting strings to ints is your bottleneck, you've got bigger things to worry about
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    106
    Aren't sstream and atoi both faster than the booth method? And don't they also both have cleaner syntax? And, er, don't they also not require you to use boost, which... isn't really standard?

  8. #8
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    Probably, no and yes, and yes. But lexical_cast is "simple and elegant, but also typesafe and extensible," which cannot be said for the other two choices. Most Boost libraries are also portable and tested thoroughly just like standard libraries, so much that many are being added to the standard.

    There are many reasons to use boost in your app, and if you are using it already, then lexical_cast is an excellent solution to the conversion problem.

  9. #9
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,892
    Quote Originally Posted by suzakugaiden
    Aren't sstream and atoi both faster than the booth method?
    atoi is faster. sstream, not noticeably. See these benchmarks:
    http://www.gotw.ca/publications/mill19.htm
    (Note that these are old and outdated - more up-to-date benchmarks could be interesting, as C++ standard libraries tend to get better.)

    And don't they also both have cleaner syntax?
    stringstream cleaner syntax than lexical_cast? Are you kidding?
    Actually, I prefer the very clear lexical_cast even over the cryptic acronym "atoi".

    And, er, don't they also not require you to use boost, which... isn't really standard?
    So? Boost is freely available, usable without charge or limitation for both commercial and non-commercial projects, compatible with the GPL, extremely widely used, tested, peer-reviewed and documented, maintained by a group of people many of whom are on the C++ standards committee, work on most compilers out there (lexical_cast in particular), ... what more do you want?
    Last edited by CornedBee; 01-18-2006 at 06:13 PM.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  10. #10
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    Quote Originally Posted by CornedBee
    So? Boost is freely available, usable without charge or limitation for both commercial and non-commercial projects, compatible with the GPL, extremely widely used, tested, peer-reviewed and documented, maintained by a group of people many of whom are on the C++ standards committee, work on most compilers out there (lexical_cast in particular), ... what more do you want?
    in short, "b00s7 pwns u"

    It rules. I honestly think I'd cry if someone made me go back to programming C++ without boost.bind and boost.lambda. And don't get me started on the smart pointers...
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  11. #11
    Super Moderater.
    Join Date
    Jan 2005
    Posts
    374
    This code will put the integer value into temp. It will also disregard any alpha characters after the int.
    IMO I don't think you can reply completely on either, stringstream, atoi or boost functions.

    Take for example stringstream.

    Let's say you ask the user to type in a number at the command line, and by accident they enter:

    Code:
    1234bd
    Ok, that's not going to be a problem since stringstream would truncate the input to 1234 ignoring the alphanumeric input.

    However, what happens if they type:

    Code:
    1234b3432
    And the only mistake was they hit 'b' by accident.
    Stringstream will just assume they meant to type 1234 and ignore all the rest.Clearly in this example there is a sense of ambiguity.

    Sometimes when you are writing a parser you have to ensure you go through all the specific cases that may throw up errors.

    I mean when I was writing my univarte equation solver,relying solely on stringstream or boost would have not worked. Boost is an excellent resource, however, sometimes you have to do it the hard way and ensure every exception is accounted for.

  12. #12
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    However, what happens if they type:

    Code:

    1234b3432
    Garbage In = Garbage out

    I don't see the problem, check your input first, then call your preference of conversion

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to combine these working parts??
    By transgalactic2 in forum C Programming
    Replies: 0
    Last Post: 02-01-2009, 07:19 AM
  2. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  3. Debug Error Really Quick Question
    By GCNDoug in forum C Programming
    Replies: 1
    Last Post: 04-23-2007, 12:05 PM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. Quack! It doesn't work! >.<
    By *Michelle* in forum C++ Programming
    Replies: 8
    Last Post: 03-01-2003, 11:26 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21