Jump to content
  • Advertisement
Sign in to follow this  
kakum

C char * to int

This topic is 3724 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to convert char * to int. I'm being restricted to use of C, not C++, so std::string is out. (int) '3' returns 51, so I'm not sure what's up with that. Any suggestions?

Share this post


Link to post
Share on other sites
Advertisement
51 is the ASCII code for the character '3'. Check an ASCII table for a complete list of characters. Your method of conversion is correct.

EDIT: Ninja'd!

Share this post


Link to post
Share on other sites
Quote:
Original post by Dave
atoi()


Avoid atoi! atoi() has very poor error checking capabilities. 0 can indicate either an error or a successful conversion from "0" and isn't required to set errno.

Use strtol or strtoul.

Share this post


Link to post
Share on other sites
Quote:
Original post by the_edd
Quote:
Original post by Dave
atoi()


Avoid atoi! atoi() has very poor error checking capabilities. 0 can indicate either an error or a successful conversion from "0" and isn't required to set errno.

Use strtol or strtoul.

Yeah atoi() is the quick and dirty way to do it.
Strtol is now the preferred method.

// crt_strtod.c
// This program uses strtod to convert a
// string to a double-precision value; strtol to
// convert a string to long integer values; and strtoul
// to convert a string to unsigned long-integer values.
//

#include <stdlib.h>
#include <stdio.h>

int main( void )
{
char *string, *stopstring;
double x;
long l;
int base;
unsigned long ul;

string = "3.1415926This stopped it";
x = strtod( string, &stopstring );
printf( "string = %s\n", string );
printf(" strtod = %f\n", x );
printf(" Stopped scan at: %s\n\n", stopstring );

string = "-10110134932This stopped it";
l = strtol( string, &stopstring, 10 );
printf( "string = %s\n", string );
printf(" strtol = %ld\n", l );
printf(" Stopped scan at: %s\n\n", stopstring );

string = "10110134932";
printf( "string = %s\n", string );

// Convert string using base 2, 4, and 8:
for( base = 2; base <= 8; base *= 2 )
{
// Convert the string:
ul = strtoul( string, &stopstring, base );
printf( " strtol = %ld (base %d)\n", ul, base );
printf( " Stopped scan at: %s\n", stopstring );
}
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!