Reputation: 41
Im doing some work for Uni and wrote a programm which stores Integers in an char Array and converts them to their ASCII Values and prints them at the end. My code did not work before and only started working when i changed "%c" to "%i" in my scanf line. My question: Why does it have to be "%i" when i wanna store those Numbers in an char Array and not an Int Array. Thanks!
My code:
#include <stdio.h>
int main()
{
int i; /counter
char numbers[12];
printf("Please enter 12 Numbers\n");
for(i = 0; i < 12; i++){
printf("please enter the %i. Number\n", i+1);
scanf("%i", &numbers[i]);// <-- changed "%c" to "%i" and it worked.why?
}
for(i = 0; i < 12;i++){
printf("The %i.ASCII value is %i and has the Char %c\n", i+1, numbers[i], numbers[i]);
}
return 0;
}
Upvotes: 0
Views: 563
Reputation: 2813
%c
is for reading a single character. So for example if you type in "123"
, scanf
will read '1'
into the char
variable and leaves the rest in the buffer.
On the other side %i
is the specifier for int
and will therefore lead to undefined behavior when trying to read in a char
.
I think what you are looking for is the %hhi
specifier, which reads a number into a char
variable.
Upvotes: 1