46

Possible Duplicate:
How to parse a string to an int in C++?

How do you convert a C++ string to an int?

Assume you are expecting the string to have actual numbers in it ("1", "345", "38944", for example).

Also, let's assume you don't have boost, and you really want to do it the C++ way, not the crufty old C way.

Community
  • 1
  • 1
krupan
  • 3,920
  • 5
  • 27
  • 24
  • 13
    How about some of the examples from the following: http://www.codeproject.com/KB/recipes/Tokenizer.aspx They are very efficient and somewhat elegant. –  Nov 04 '10 at 01:51

8 Answers8

74
#include <sstream>

// st is input string
int result;
stringstream(st) >> result;
Mark Lakata
  • 19,989
  • 5
  • 106
  • 123
Randy Sugianto 'Yuku'
  • 71,383
  • 57
  • 178
  • 228
  • 3
    What if there is an error? Say the string doesn't have a number in it ("hello!" instead of "5"). – krupan Oct 14 '08 at 18:05
  • 21
    Then you check for the error: (stringstream(st) >> result) ? cout << result : cerr << "You lose"; – Robᵩ Oct 14 '08 at 19:50
34

Use the C++ streams.

std::string       plop("123");
std::stringstream str(plop);
int x;

str >> x;

/* Lets not forget to error checking */
if (!str)
{
     // The conversion failed.
     // Need to do something here.
     // Maybe throw an exception
}

PS. This basic principle is how the boost library lexical_cast<> works.

My favorite method is the boost lexical_cast<>

#include <boost/lexical_cast.hpp>

int x = boost::lexical_cast<int>("123");

It provides a method to convert between a string and number formats and back again. Underneath it uses a string stream so anything that can be marshaled into a stream and then un-marshaled from a stream (Take a look at the >> and << operators).

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Martin York
  • 257,169
  • 86
  • 333
  • 562
  • shouldn't that be "if (!x)..."? – Svante Nov 20 '08 at 03:31
  • 5
    No. If the stream operator fails extracting a number from str it sets the bad bit. Using this in a boolean context (as above) will test to see if the stream is OK by returning an object that is convertable to bool. If I tested 'x' then it would fail if the value put in 'x' is 0. If the stream failed to extract anything the value of 'x' is undefined. – Martin York Apr 17 '09 at 18:43
  • 1
    It sets the _fail_ bit, not the _bad_ bit. operator! is a synonym for fail(). – scai Aug 01 '12 at 14:19
4

I have used something like the following in C++ code before:

#include <sstream>
int main()
{
    char* str = "1234";
    std::stringstream s_str( str );
    int i;
    s_str >> i;
}
ayaz
  • 10,406
  • 6
  • 33
  • 48
4

C++ FAQ Lite

[39.2] How do I convert a std::string to a number?

https://isocpp.org/wiki/faq/misc-technical-issues#convert-string-to-num

Alessandro Jacopson
  • 18,047
  • 15
  • 98
  • 153
2

Let me add my vote for boost::lexical_cast

#include <boost/lexical_cast.hpp>

int val = boost::lexical_cast<int>(strval) ;

It throws bad_lexical_cast on error.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Ryan Ginstrom
  • 13,915
  • 5
  • 45
  • 60
0

Use atoi

Ramesh Soni
  • 15,867
  • 28
  • 93
  • 113
  • Not particularly C++ is it? Even std::atoi isn't really C++... – graham.reeds Oct 25 '08 at 20:08
  • 2
    atoi() does other magic... like ignoring leading whitespace, ignoring trailing non-whitespace, and assuming "0" is a valid error condition as well. Please only use atoi() when you really don't care about validity. Otherwise, strtod() in C and std::istringstream in C++. – Tom Barta Nov 20 '08 at 03:18
0

Perhaps I am misunderstanding the question, by why exactly would you not want to use atoi? I see no point in reinventing the wheel.

Am I just missing the point here?

user12576
  • 378
  • 1
  • 2
  • 9
  • The manual page for atoi() says, "The atoi() function is subsumed by strtol() but is retained because it is used extensively in existing code. If the number is not known to be in range, strtol() should be used because atoi() is not required to perform any error checking." – krupan Oct 14 '08 at 17:50
  • I though atoi() was non standard thus not available everywhere. Could be wrong though. – Martin York Oct 14 '08 at 18:41
  • That's an excellent point, Krupan. I admit I had not thought of that. – user12576 Oct 15 '08 at 11:39
  • atoi() also ignores leading whitespace and trailing crap, so it may succeed where other more strict parsers will fail. Depending on your POV, that could be an advantage or a hindrance. – Tom Barta Nov 20 '08 at 03:19
-6

in "stdapi.h"

StrToInt

This function tells you the result, and how many characters participated in the conversion.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
user27732
  • 23
  • 1
  • 2
    Huh? Googling for this "stdapi.h" doesn't turn up anything. Do you mean "shlwapi.h" (which is Windows-specific, part of the shell DLL, and equivalent to the crufty old C ways)? – bk1e Oct 14 '08 at 05:57