views:

8428

answers:

9

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.

+11  A: 

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<>

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).

Martin York
shouldn't that be "if (!x)..."?
Svante
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
A: 

Use atoi

Ramesh Soni
Not particularly C++ is it? Even std::atoi isn't really C++...
graham.reeds
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
+23  A: 
// st is input string
int result;
stringstream(st) >> result;
yuku
What if there is an error? Say the string doesn't have a number in it ("hello!" instead of "5").
krupan
Then you check for the error:(stringstream(st) >> result) ? cout << result : cerr << "You lose";
Rob Adams
A: 

in "stdapi.h"

StrToInt

This function tells you the result, and how much characters perticipated in the conversion.

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
A: 

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
OK. Someone already suggested this, so I've upped their.
ayaz
+8  A: 

This is, more or less, a duplicate of How to parse a string to an int in C++?

bk1e
The accepted answer posted by jk: You can use Boost's lexical_cast, which wraps this in a more generic interface. lexical_cast<Target>(Source) throws bad_lexical_cast on failure.
eed3si9n
This should be a comment on the question, you deserve no juice for this answer.
Aidan Ryan
It deserves upvotes from those who find it useful; nothing wrong with that.
romkyns
A: 

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?

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
I though atoi() was non standard thus not available everywhere. Could be wrong though.
Martin York
That's an excellent point, Krupan. I admit I had not thought of that.
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
+1  A: 

C++ FAQ Lite

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

http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2

uvts_cvs
best approach, imho, especially with the configurable fail_on_leftover
Eli Bendersky
What is the "fail_on_leftover"?
uvts_cvs
+1  A: 

Let me add my vote for boost::lexical_cast

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

It throws bad_lexical_cast on error.

Ryan Ginstrom