By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,379 Members | 3,035 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,379 IT Pros & Developers. It's quick & easy.

Converting strings into integers

P: 1
Hi,

I'm a newbie in the matter of C++.
Now i'm trying to convert a text from a string (like str = "123") into an int-variable.
In Java i've used parseInt for this function, but i can't find the C++-equivalence.
I rather use a string and not a char-array...

Idea someone?

Thx in advance,
Misko
Aug 11 '07 #1
Share this Question
Share on Google+
3 Replies


Meetee
Expert Mod 100+
P: 931
Hi,

I'm a newbie in the matter of C++.
Now i'm trying to convert a text from a string (like str = "123") into an int-variable.
In Java i've used parseInt for this function, but i can't find the C++-equivalence.
I rather use a string and not a char-array...

Idea someone?

Thx in advance,
Misko
Hi Misko,

You can use atoi function for that.
Usage is like this:

int value = atoi ( const char * str );

This requires char array as const char * is passed as a parameter.

Regards
Aug 11 '07 #2

weaknessforcats
Expert Mod 5K+
P: 9,197
atoi() is deprecated in C++.

Use a stringstream.
Expand|Select|Wrap|Line Numbers
  1. int result;
  2. string str("123");
  3. stringstream ss;
  4. ss << str;
  5. ss >> result;
  6.  
Aug 11 '07 #3

PieCook
P: 9
I was just about to suggest a custom-made function, but the other ones look far better. I was going to do something like this:

Expand|Select|Wrap|Line Numbers
  1.  
  2. int sum = 0;
  3. int length = strlen(str);
  4. for (i = length - 1; i >= 0; i--)
  5.     sum += str[i] * pow(10, length - i);
  6.  
  7.  
I did not run the code, so it might have a bug or two, but you get the idea.
Aug 13 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.