How do you convert a C++ string to an int? [duplicate]
Asked Answered
N

8

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.

Name answered 14/10, 2008 at 5:35 Comment(1)
How about some of the examples from the following: codeproject.com/KB/recipes/Tokenizer.aspx They are very efficient and somewhat elegant.Adelbert
U
74
#include <sstream>

// st is input string
int result;
stringstream(st) >> result;
Uttasta answered 14/10, 2008 at 5:44 Comment(2)
What if there is an error? Say the string doesn't have a number in it ("hello!" instead of "5").Name
Then you check for the error: (stringstream(st) >> result) ? cout << result : cerr << "You lose";Brade
L
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).

Lenette answered 14/10, 2008 at 5:37 Comment(3)
shouldn't that be "if (!x)..."?Crayon
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.Lenette
It sets the fail bit, not the bad bit. operator! is a synonym for fail().Graduation
Z
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;
}
Zephyrus answered 14/10, 2008 at 5:48 Comment(1)
OK. Someone already suggested this, so I've upped their.Zephyrus
M
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

Michi answered 15/10, 2008 at 17:45 Comment(2)
best approach, imho, especially with the configurable fail_on_leftoverDichlorodifluoromethane
What is the "fail_on_leftover"?Michi
S
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.

Squish answered 20/11, 2008 at 0:54 Comment(0)
K
0

Use atoi

Keirakeiser answered 14/10, 2008 at 5:39 Comment(2)
Not particularly C++ is it? Even std::atoi isn't really C++...Cahoot
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++.Mucoid
D
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?

Depilatory answered 14/10, 2008 at 11:57 Comment(4)
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."Name
I though atoi() was non standard thus not available everywhere. Could be wrong though.Lenette
That's an excellent point, Krupan. I admit I had not thought of that.Depilatory
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.Mucoid
O
-6

in "stdapi.h"

StrToInt

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

Otho answered 14/10, 2008 at 5:45 Comment(1)
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)?Segarra

© 2022 - 2024 — McMap. All rights reserved.