I was trying to create the following program:
#include <stdio.h>
#include <stdlib.h>
int main(){
int grade;
while( (grade = getchar()) != EOF){
printf("grade is currently %c \n" , grade); /*added this line to confirm my suspicion that somehow my "enter" input was being registered for some reason*/
switch(grade){
case 'a':
printf("you got an a!\n");
break;
case 'b':
printf("you got a b!\n");
break;
default:
printf("error :(\n");
break;
}
}
printf("Hello world!\n");
return 0;
}
However, i seem to get two outputs when i enter the character 'a'. The first ouput is as per expected i.e it prints "you got an a!". However, after that I seem to get a second output which is the "default" case. And I realise that this was because the program was somehow reading my "enter" as an input? Is there a way to prevent this? I am a little concerned as this code is nearly identical to a source code given to me from a textbook so I thought that this code should not be malfunctioning as it is :(
Also, can anyone help guide me as to how this program reads my input without a scanf? And why can the grade variable, which was declared as an integer, receive character inputs?