0

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Javier Lam
  • 21
  • 3
  • Simply add a case that handles the '\n' (by doing nothing) ? – Unimportant Dec 08 '16 at 11:54
  • That works! However, just for my own understanding, why does it read my enter input?:( Its a little frustrating for me as my textbook didnt point out that such a malfunction would occur although my code is identical! – Javier Lam Dec 08 '16 at 11:57
  • Why wouldn't it return the newline? The newline char is as valid a char as any other. If you have no use for it, discard it yourself. But it's read so it can be used if you want to. – Unimportant Dec 08 '16 at 12:02
  • If you want to read a *line*, why are you using a function that reads a *character*? And if you use a function that reads a *character*, why are you surprised when it reads, well, every character? – David Schwartz Dec 08 '16 at 12:03
  • hmm okay that makes sense... thanks everyone I guess I assumed it worked like a scanf( "%c" , grade)... Is there another way I can go aboutdoing this without using the getchar() function but still maintaining this switch/while structure? – Javier Lam Dec 08 '16 at 12:23

0 Answers0