Hi,

I'm a freshman in computer science and a new member to this forum. I'd like to convert the string representation of a number e.g "456" into its integer equivalent i.e. 456.

As for character representation of single digits e.g. "6", I'm able to convert it to its integer equivalent by doing:
char myChar = "6";
int asciiVal = myChar - '0'; //produces the integer 6 now.

Could anyone show me how the string representation of a number like "456" can be converted to its integer equivalent?

Thanks
Danny

there's a function to do just that in the standard library by the name of atoi (ASCII to Integer).

Use it this Way

char a[]="123";
char b[]="123.66";
//for interger
int i=atoi(a);

//for Long

long l=atol(a);

//for double

float d=atof(b);

Hope this will help you

Could anyone show me how the string representation of a number like "456" can be converted to its integer equivalent?

#include <stdio.h>

int main(void)
{
   int i, value;
   const char text[] = "456";
   for (i = 0, value = 0; text [ i ] != '\0'; ++i)
   {
      [B]value *= 10;[/B]
      [I]printf("value *= 10 = %3d, ", value);[/I]
      [B]value += text [ i ] - '0';[/B] /* add value of current digit character */
      [I]printf("value += '%c' - '0' = %3d\n", text [ i ], value);[/I]
   }
   return 0;
}

/* my output
value *= 10 =   0, value += '4' - '0' =   4
value *= 10 =  40, value += '5' - '0' =  45
value *= 10 = 450, value += '6' - '0' = 456
*/

[edit]Or another way of looking at it:

#include <stdio.h>

int main(void)
{
   int i, value;
   const char text[] = "456";
   for ( i = 0, value = 0; text [ i ] != '\0'; ++i )
   {
      [B]int digit = text [ i ] - '0';[/B] /* get value of current digit character */
      [I]printf("value = %3d, %3d * 10 = %3d, ", value, value, value * 10);[/I]
      [B]value = 10 * value + digit;[/B]
      [I]printf("digit = %d, value = %d\n", digit, value);[/I]
   }
   return 0;
}

/* my output
value =   0,   0 * 10 =   0, digit = 4, value = 4
value =   4,   4 * 10 =  40, digit = 5, value = 45
value =  45,  45 * 10 = 450, digit = 6, value = 456
*/

Dave, Alok & Jwenting,

Thanks very much for the help. In fact I forgot to mention earlier when posting this problem that I'm not suppose to use built-in functions like atoi or atol for such conversions. Nevertheless, thanks to everyone for their help.
:D

Dave,
Your solution provided the answer to my problem. thanks. :D

Danny.

whilst we're on the subject is there a lib function for integer to string ect....

i tried the method above, but the segmentation fault error kept appearing.

[thread=17706]You're not passing a valid string to atol.[/thread]

whilst we're on the subject is there a lib function for integer to string ect....

Yes. itoa is the name of the function. There are corresponding functions for long or double to string. Here's an example.

#include <stdlib.h>
#include <iostream.h>

main()
{    int val;
      char st[10]
 
        val = 5 + 10;
        itoa(val,st,10) //base 10
        cout <<"decimal: "<<st<<endl;
        itoa(val,st,16)  //hexidecimal
        cout <<"hexidecimal: "<< st << endl;
}

itoa is nonstandard; sprintf is standard.

#include <iostream.h> is nonstandard; #include <iostream> is standard.

actually itoa is standardised in C++

[thread=17706]You're not passing a valid string to atol.[/thread]

i changed the code of that section.

while (passkey[x] != '\0')    // While the string isn't at the end...
    {
        passkey[x] = (int)passkey[x];    // Transform the char to int
        x++;
    }

Does that help? Does that make the code better?

Thanks so far.

Member Avatar for Siersan

actually itoa is standardised in C++

Not in my copy of the standard. What section and page are you referring to?

Does that help? Does that make the code better?

The loop doesn't do anything useful, the string that comes out will be the same string that goes in. Try running this and ignore the warning you might get about conversion from int to char.

#include <iostream>

using namespace std;

int main()
{
  char s[] = "A test string";

  for (int i = 0; s[i] != '\0'; i++)
    s[i] = int(s[i]);

  cout<< s <<endl;
}

itoa is nonstandard; sprintf is standard.

#include <iostream.h> is nonstandard; #include <iostream> is standard.

Dave is correct here, itoa() is not ANSI-C, but supported by most compilers.

Haven't you guys heard for sprintf()? it is used as printf(), just the first element must be a *char. They are defined in header cstdio.

Member Avatar for iamthwee

Haven't you guys heard for sprintf()? it is used as printf(), just the first element must be a *char. They are defined in header cstdio.

Don't bump age old posts. Let them lie in the grave where they belong. :rolleyes:

I too am stuck on this problem of converting a string to its integer equivalent. My lecturer suggested that Horner's method can be adapted to convert string characters into their integer values. E.g. "4123" becomes 4123. Would you have any idea on how to implement this or are there any alternative methods to complete such a conversion.
I guess one could extract each char in the string then convert that and so on, just have a loop?
Hope you guys can help.

Convert the string to a character array and then use atoi

/* atoi example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i;
  char szInput [256];
  printf ("Enter a number: ");
  gets ( szInput );
  i = atoi (szInput);
  printf ("Value entered is %d, and its double %d",i,i*2);
  return 0;
}

Output:
Enter a number: 73
Value entered is 73, and its double 146

As if bumping an old thread wasn't bad enough, you had to use gets() and atoi() to do it.

commented: Fixing erroneous neg rep. +13

Hi people:

As stated in our posting rules, we ask that members not tag their questions on to a thread previously started by another member (regardless of how similar your problem might seem). Not only does it divert the focus of the thread away from the original poster's problem, but it also makes it less likely that you yourself will get the individual attention that you need.

Please start your own thread and post your question there. When you do, please give us as much specific info as possible regarding the problem (exact error messages, system specs, troubleshooting steps you've already tried, etc.).

For a full description of our posting guidelines and general rules of conduct, please see this page:

http://www.daniweb.com/techtalkforums/faq.php?faq=daniweb_policies

Thanks for understanding.

I didn't resurrect it...I just answered t. Don't shoot the messenger.

If you have a better solution, share it.

I didn't resurrect it...I just answered t. Don't shoot the messenger.

What makes you think DMR was talking specifically to you? "Hello People" was the post salutation. The others could be people, too. :)

I wasn't responding to DMR, I was responding to Salem.

DMR snuck that in while I was typing...lol.

I wasn't responding to DMR, I was responding to Salem.

DMR snuck that in while I was typing...lol.

Oh... :cheesy: That's why I usually quote who I'm responding to. It's really hard to follow generic comments when people sneak in....

But you did use gets() which is still a no-no.

Dead horse beaten.
<<thread closed>>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.