Converting a char to an integer

Hello everyone,

I'm writing a program and I've been implementing a way for the user to type strings of integers which are then parsed and converted from char into int. For the actual conversion of char into int, I used this method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
char userinput[18]; //this stores the user's input as a string

int intarray[8]; //this will store the parsed integers

int n=0; //the number of parsed digits

int i;

for (i=0; i<18; i++)
{

   if (userinput[i]>='0' && userinput[i]<='9') //if character is a digit
     {
   	   intarray[n] = userinput[i] - '0'; //convert char to integer
	   n++; 
     }

}



I have a question regarding line 14, which involves the operation:

intarray[n] = userinput[i] - '0'; //convert char to integer

I have found this method of conversion through the internet, but am not sure how it actually works. I was hoping for some elaboration on this. Essentially, what it does is that it subtracts the character '0' from the character stored in userinput[i], and stores it in an integer variable.

Before this conversion, I have found that userinput[i] stores an ASCII value (so if the digit typed by the user was 4, the stored value would be 52, and so on). But how does this subtraction convert this ASCII value to an integer? What does it "do", essentially?

Thank you for any help or feedback. It is most appreciated.

Regards,

Okaya
Last edited on
The ASCII character '0' is equivalent to the integer 48. If userinput[i] is the ASCII character '4', for example, this is equivalent to the integer 52 as you wrote above. Now the type of intarray[n] is an integer, so there is an implicit conversion from both of the right-hand-side operands to integer, hence giving (52-48) = 4.

Does that answer your question, or did I miss something?
Yes, it does, thank you very much sammy34. I appreciate the response.

I confused the ASCII 'NUL' (whose value is 0) with the ASCII '0' whose value is 48. Thank you for clarifying this up for me.

Okaya

Topic archived. No new replies allowed.