Sign in to follow this  
kakum

C char * to int

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this