The sample of the program is as follow:
int main(void)
{
char input;
printf("\nEnter phone number: ");
while ((input = getchar()) != '\n') {
switch (toupper(input)) {
case 'A': case 'B': case 'C':
printf("2");
break;
case 'D': case 'E': case 'F':
printf("3");
break;
case 'G': case 'H': case 'I':
printf("4");
break;
case 'J': case 'K': case 'L':
printf("5");
break;
case 'M': case 'N': case 'O':
printf("6");
break;
case 'P': case 'R': case 'S':
printf("7");
break;
case 'T': case 'U': case 'V':
printf("8");
break;
case 'W': case 'X': case 'Y':
printf("9");
break;
default:
putchar(input);
}
}
printf("\n\n");
return 0;
}
My question is, how on Earth does the flow here work? I can't seem to understand the path the program took. Does the char
variable magically become an array? How is it that putchar()
prints the entire line instead of the first character entered? How exactly does something that's supposed to get and print one character, reads and prints an entire line of characters while altering them with the switch statement? Does it test each char
as its entered? But then how is the string printed as a string?
Edit: I've done some research and I read about a keyboard buffer, which seems to be the cause of my confusion. To my knowledge, getchar()
and putchar()
receives and outputs a single character. I'm aware that the loop asks continuously for the next "buffered" char when the getchar()
comes back around, still a bit confused by I should get it, but what's more confusing is putchar()
. At the end of the loop, when it breaks and goes to the condition, does it print that one character then continues and prints the other one by one with each execution of the loop? Only stopping the loop at which point the new line was read? And if so, only what was previously printed, is displayed on the screen? And then if that's the case then the printed chars would print in line next to each other with each execution, giving the illusion of a string? I need confirmation on this and also, when is the char
discarded and replaced? After its printed? And at which line does it receive the next
char in the buffer queue?