I have a string char * a = '343'. I want to convert it into integer value.
Example. char *a = "44221" I want to store that value into into int a;
I have a string char * a = '343'. I want to convert it into integer value.
Example. char *a = "44221" I want to store that value into into int a;
This is is part of most C runtimes:
#include <stdlib>
char *a = "1234";
int i = atoi(a);
That's the atoi
function. Do read through the various methods available. C's library is pretty lean so it won't take long.
There are several ways to convert a string (pointed at by a char *
) into an int
:
I'm listing few of them here:
Let's assume you have a string str
declared as:
char *str = "44221";
int a = atoi(str);
This returns the int
value converted from the string pointed at by str
. Although convenient, this function does not perform accurate error reporting when user supplies an invalid input.
Using sscanf(): This is similar to the usual scanf
except that it reads input from a string rather than from stdin
.
int a;
int v = sscanf(str, "%d", &a);
// XXX: v should be 1 since 1 conversion is performed; handle the conversion error if it isn't
strtol: This converts a given string to a long integer. Documentation found at: http://man7.org/linux/man-pages/man3/strtol.3.html
General usage:
char *ptr;
long a = strtol(str, &ptr, base);
The address of the first invalid character (not a digit) is stored in ptr
. Base is by default 10.
Iterating through character values: Why depend on libraries when you can write your own routine to achieve this? It isn't hard at all. That way you can even perform the required validation/error checking.
Sample code:
unsigned char ch;
int a = 0;
// Add checks to see if the 1st char of the string is a '+' or '-'.
for (i = 0; i < strlen(str); i++) {
ch = str[i];
//Add error checks to see if ch is a digit or not (e.g. using isdigit from <ctype.h>).
a = a*10 + (ch - '0');
}
Hope this helps!
This should help
#include <stdlib.h>
inline int to_int(const char *s)
{
return atoi(s);
}
just in case for an example usage
int main( int ac, char *av[] )
{
printf(" to_int(%s) = %d " ,av[1] , to_int(av[1]) );
return 0;
}