# Converting string to integer...

• 01-25-2003
Ham
Converting string to integer...
Say I have a string (str) that contains a very long signed integer, like +1234567890 or -1234567890. How can I convert this string to an integer value that will preserve all 10 values (including the sign would be nice too)? I've tried functions like atol but it doesn't work. A small code example should suffice.

Thanks.
• 01-25-2003
Jeremy G
This seemed to work perfectly fine for me:

Code:

```#include <iostream.h> #include <windows.h> #include <stdio.h> int main() {         char strNumber[20] = "-3003820";         long number;         //strNumber[0] = '0';         number = strtol( strNumber, '\0', 10 );         printf("String was: %s, number is: %i", strNumber, number );         return 0; }```
• 01-25-2003
joshdick
Search the board. Not too long ago there was a thread full of information on this topic. I believe it was called 'atoi??' or something like that. Always search the board before posting a question.
• 01-25-2003
Ham
Nice try, but that didn't work for numbers like +9999999999. Searching the board didn't really help. Any takers?
• 01-25-2003
rmullen3
~
Here's my stab at it:

Code:

```long bigatoi (const char* n) {         int neg = 0;         if (n[0] == '-')                 neg = 1;                 int l = strlen(n);         int i = neg;         long c = pow(10,(l-1-neg));         long num = 0;         for (; i < l; ++i)         {                 num += ((int)(n[i]-48) * c);                 c /= 10;         }         if (neg)                 return -num;         return num; }```
There's plenty of ways that code could be better, I'm sure.

The problem is that really big numbers are require more space. You can replace the long c =, long num = and return type with long doubles, which have more space (tried it but numbers come back in sci. notation)...

I'll try to improve this code...
• 01-25-2003
rmullen3
~
I dunno how to get it to work with bigger numbers =)

Another way would be to create (or use a preexisting, perhaps) "big number" class, that can store and work with numbers with very long digit counts.
• 01-26-2003
Sebastiani
Code:

``` int  as_int(const char c) {  return c - 0x30; } template <class number> number  power(number value, int exp) {  if(exp < 1) return 1;  number result = value;     while(--exp)   {     result *= value;   }  return result; } template <class number> number  aton(const char * input) {  int x = 0;  number value = 0;  char * p = (char*)&input[ strlen(input) ];   while(p != &input[0])  {     --p;       if(isdigit(*p))     {       value += ( as_int(*p) * power<number>(10, x++) );     }     else if(*p == '-')     {       value = -value;     }   }  return value; } int main(){ char buff[100];   do   {     cout << "...enter a number, '0' to exit..." << endl;     cin.getline(buff, 100);     cout << aton<long long int>(buff) << endl;   }while(aton<long long int>(buff) != 0);  cin.get(); return 0; }```