Hey,can u ppl tell me a simple way of converting a string into a integer?

I have something like

string str1 ("1000");
string str2 ("2000");

i wanna convert them into integers and add them,any idea how?

9 Years
Discussion Span
Last Post by TrintiyNoe

the only way i can think of is to read the string one character at a time, and convert it in this way:

First make an int for the holding of the sum. Then repeatedly multiply it by 10 and add add the character of the string that you are on and move to the next character.

for example:

string: 1234

int sum=0;

obviously you would need to implement the code to find each digit individually at first.

if (character=="1")

you should also include something to make sure that all the characters in the string are actually numbers.

If you expect to have decimal points you will need to have another variable to keep track of how many numbers come after it. Once you know that you divide your sum by 10^number_of_decimal_places.

int decimal_divide=1; //Note the 1

for (int i=0; i<number_of_decimal_places; i++)

Hope this helps :)


I guess I would use the C++ way of doing it with stringstream Though people prefer using atoi() which is not a standard and which is basically the "C" way of doing it :)

#include <iostream>
#include <sstream> //required for conversion.
#include <string>

using namespace std;

int main()
   string str="1991"; //Contains a string.
   stringstream convert; //Make a stringstream.
   convert<<str; // Put the value of str into the string stream.
   int num;
   convert>>num; // Get the value back into a integer. 

>Though people prefer using atoi() which is not a standard and which is basically
>the "C" way of doing it
atoi is as standard as the stringstream solution. The only problem is that it is not that 'good'.
By good means that as the stringstream solution will rely on the standard iostream library, it will tend to be more robust.
One have plenty of good reasons to choose iostream rather than the C cstdio which are listed here.

The stringstream is elegant albeit slow. But as the rules says: `` Don't care about small optimization until you profile your code"

My final advice : use string stream in general and use atoi if speed is an issue.


use string stream in general and use atoi if speed is an issue.

That's close to my advice. But I say use strtol because atoi doesn't have any error handling capability. Boost:lexical_cast and Boost::numeric_cast are even simpler than ad hoc string stream code or robust strtol code, but you have to have Boost to use them.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.