Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   Convert String to Int (http://www.programmingforums.org/showthread.php?t=12011)

Cool1Net6 Nov 27th, 2006 5:21 AM

Convert String to Int
 
In a recent contest, the problem was to reverse the digits of a number and add that new number to the old number to come up with a newer number. I had the knowledge to reverse the digits of a number by converting the original number to a string and swapping the positions of each character, but to add this new number to the original number, I needed to convert the new number back to an int. I lost the competition because I lacked this knowledge.

How do you convert a String to an Int?

-Cool-

kruptof Nov 27th, 2006 5:43 AM

you could of done string.c_str() which would return you the string in an const char* format then you could loop through that new constant array of characters and convert each one to an number use atoi or something else, some else reccommended.

Soulstorm Nov 27th, 2006 7:10 AM

The easiest way to do it is to use a stringstream

example:

:

  1. #include <iostream>
  2. #include <sstream>
  3.  
  4. int main (int argc, char * const argv[]){
  5.         std::stringstream s("2903");
  6.         int i;
  7.  
  8.         s >> i;
  9.         std::cout << i+100;
  10.  
  11.  
  12.         return 0;
  13. }

Probably a bad example, but it should give you an idea on what to do. Give to an std::stringstream the number you want as a constant character, or an std::string and extract it to an integer or enything else you want.

You could also use atoi(), but using stringstreams will be a lot easier for you and a lot more comprehensive.

The STL has many things you should read when you encounter a problem. In many occasions, the STL solves the problem. Check this out for a reference.

Lesliect6 Nov 27th, 2006 7:51 AM

Hello Coll1Net6,

Converting a string to an int is very easy, having in mind that a string is only a representation of a number in the ASCII chart. Having also in mind that a string is nothing more than an array of chars, you can easily manipulate each individual character. So, if your string is composed only of numbers in string format (like '4' or '6'), all you have to do is :

:

int number = string[x] - 48;

where x is the index of the char you want converted to int.

And the job is done.

DaWei Nov 27th, 2006 8:11 AM

Leslie, your method is contingent upon the characters being in an ASCII representation. Such is not always the case. One should use string streams, as recommended, or perhaps strtol or similar. Atoi is not a good choice because errors are indistinguishable from converting the value, zero (and other badnasty results).

pegasus001 Dec 7th, 2006 12:47 PM

int string_to_int(string number)
{
int num = 0;
int temp = 1;

for (int i = number.length; i >= 0; i--)
{
num += atoi(number[i]) * temp;
temp *= 10;
}

return num;
}

Narue Dec 7th, 2006 1:38 PM

>for (int i = number.length; i >= 0; i--)
That's an off-by-one error and a syntax error. You want to start at number.length() - 1.

>num += atoi(number[i]) * temp;
Okay, number is a string, so number[i] is a character. That alone is a type mismatch. You could take the address of that character because atoi expects a C-style string (any number of characters terminated with '\0'), but the string class doesn't guarantee that internal representation.

The good news is that your algorithm only expects single characters at a time, so you can use the subtraction trick to turn something like '5' into 5:
:

num += (number[i] - '0') * temp;
Then your only problem is when the string doesn't represent a valid integer.

DaWei Dec 7th, 2006 1:58 PM

Are you people reading the responses? ATOI is not a good thang. Here's a quote from cplusplus (emphases mine):
Quote:

Return Value.

The converted integer value of the input string.
On overflow the result is undefined.
If an error occurs 0 is returned. (How do you know whether it's an error, or a conversion of zero?)
Using this is essentially dereliction, like using 'gets'.

I have modified Soulstorm's code to present some alternatives. All are easy. It's certainly preferable to looping through a set of characters and calling atoi, when there's no guarantee that each of the characters is convertible.
:

#include <iostream>
#include <sstream>
#include <string>

int main (int argc, char * const argv[])
{
    int myInt;
    std::string aString = "3092";
    char cString [] = "2903";

    // Use a C string
    std::stringstream withCString (aString.c_str ());
    // Use another C string
    std::stringstream withCString2 (cString);
    // Use a string-class string
    std::stringstream withString (aString);

    withCString >> myInt;
    std::cout << myInt << std::endl;
    withCString2 >> myInt;
    std::cout << myInt << std::endl;
    withString >> myInt;
    std::cout << myInt << std::endl;;
 
    return 0;
}

Output:
Quote:

3092
2903
3092
EDIT: Woops, was off keying in the code while Narue posted.

pegasus001 Dec 9th, 2006 12:42 PM

Quote:

Originally Posted by Narue (Post 120771)
>for (int i = number.length; i >= 0; i--)
That's an off-by-one error and a syntax error. You want to start at number.length() - 1.

I forgot, about that.

Quote:

Originally Posted by Narue (Post 120771)
>num += atoi(number[i]) * temp;
Okay, number is a string, so number[i] is a character. That alone is a type mismatch. You could take the address of that character because atoi expects a C-style string (any number of characters terminated with '\0'), but the string class doesn't guarantee that internal representation.

The good news is that your algorithm only expects single characters at a time, so you can use the subtraction trick to turn something like '5' into 5:
:

num += (number[i] - '0') * temp;
Then your only problem is when the string doesn't represent a valid integer.

Well we can arrange that with a switch statement, what do you think????:beard: :cool:

DaWei Dec 9th, 2006 1:50 PM

I think you're not paying attention to the responses. Next question?


All times are GMT -5. The time now is 1:32 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC