Converting an String to an Integer

I retrieve a string from a file that contains only numbers. Now I want to convert it into a integer form to perform arithmetic operations on it.
Is there a way to do so?

PS: I have tried using atoi and it doesn't work. It gives the error:
'atoi' : cannot convert parameter 1 from 'std::string' to 'const char *'
Last edited on
closed account (zb0S216C)
You need to call the c_str( ) member of your string instance. For example: atoi( str.c_str( ) )

Wazzak
Last edited on
Or (preferably in my opinion) you can use a stringstream.
+1 for string streams. You can check the mechanics here: http://ideone.com/dYJMM .
@Framework: That worked. Thanks! But what does c_str() do?

@ultifinitus&webJose: could you tell me how to use stringstreams for string to int conversion?
The link posted be WebJose was a bit too advanced for me.
closed account (zb0S216C)
Nisheeth wrote:
But what does c_str() do?

The name gives it away. It returns a C-string that's the equivalent to your string object.

Wazzak
Streams know how to convert many (if not all) native data types to a string. So basically, you use a special stream that bases its storage in a string object (therefore the name "stringstream") to "input" and "output" strings to and from data types. That's all. The rest that you see in the code is to make sure, for example, that all data in the string is used in the conversion (see the function FromString()). The rest is code that makes sure the conversion succeeded and that the correct number of digits are shown.
Topic archived. No new replies allowed.