In article <11**********************@g49g2000cwa.googlegroups .com>,
sophie <pa**********@gmail.com> wrote:
Read in a number as a string:
scanf("%s", &number);
number = 12345, for arguements sake
print it like this it prints '49' for the 1st char!!! Why?:
printf("number: %d\n", (int)number[0]);
Whats going on, and how do i properly convert a char to an int????!!!
You did properly convert the char to an int. The *character* '1' has
integer *value* 49 if you are using ASCII or any of several modern
encodings (but there systems where it is different.)
If you want to extract the integer value 1 from the character '1' then
you need to do one of the following, or equivilent:
if ( sscanf(number, "%d", &numberasint ) < 1 ) {
/* there was an error so do something appropriate */
}
Or
if ( isdigit( number[1] ) ) {
char nb[2];
nb[0] = number[1];
nb[1] = 0;
numberasint = atoi(nb);
} else {
/* there was an error so do something appropriate */
}
Or
{
char nb[2];
char *scannedto;
nb[0] = number[1];
nb[1] = 0;
numberasint = (int) strol(nb,&scannedto,10);
if (scannedto == nb) {
/* there was an error so do something appropriate */
}
}
Or
if ( isdigit( number[1] ) ) {
numberasint = number[1] - '0';
} else {
/* there was an error so do something appropriate */
}
--
If you lie to the compiler, it will get its revenge. -- Henry Spencer