Why is this statement printed twice in a while loop?

I wrote this simple program for practice:

#include <stdio.h> #include <stdlib.h> #include <string.h> #define CLASSES 3 #define STUDENTS 4 int grades[CLASSES][STUDENTS]; int main(void) { int i = 1; char t,k; while(i == 1) { printf("\n\n\nMENU:\nEnter the grades(E)\nReport Grades(R)\nQuit(Q)\nYour choice: "); k = toupper(getchar()); printf("Input entered... %c\n", k); switch(k) { case 'E' : printf("Entering the grades..\n"); break; case 'R' : printf("Reporting the grades...\n"); break; case 'Q' : printf("Quitting the program...\n"); exit(0); break; default: printf("ERROR: %c: Incorrect menu option\n", k); break; } } return 0; } 

When I run this, he first asks me to enter a selection. If I enter "E" or "R", it goes into the corresponding "case" block, but in the next iteration inside the while loop it does not wait for me to choose my choice. Instead, it assumes that I entered "NULL" and requested my third time. This happens every time I enter a choice. Here is the result of this program. What am I missing here?

 host-mb:c_practice host$ ./asd MENU: Enter the grades(E) Report Grades(R) Quit(Q) Your choice: E Input entered... E Entering the grades.. MENU: Enter the grades(E) Report Grades(R) Quit(Q) Your choice: Input entered... ERROR: : Incorrect menu option MENU: Enter the grades(E) Report Grades(R) Quit(Q) Your choice: R Input entered... R Reporting the grades... MENU: Enter the grades(E) Report Grades(R) Quit(Q) Your choice: Input entered... ERROR: : Incorrect menu option MENU: Enter the grades(E) Report Grades(R) Quit(Q) Your choice: Q Input entered... Q Quitting the program... host-mb:c_practice host$ 
+5
source share
1 answer

This is because you type a letter and then press the enter key. Use another getchar() to eat the trailing newline.

So change this:

 k = toupper(getchar()); 

:

 k = toupper(getchar()); getchar(); // eat the trailing newline 

When the user enters something, he goes into the stdin stream (standard input), and the system guarantees that what the user entered in the internal buffer is saved. So here is what happened to your code:

enter image description here

So the solution is the final new line !


Easter Egg Tips:

You should get the following:

 warning: implicit declaration of function 'printf' 

because you are missing the IO header, so you should add at the beginning of your main file:

 #include <stdio.h> 

Similarly, you should add:

 #include <ctype.h> // for toupper() #include <stdlib.h> // for exit() 

Another solution would be to use fgets () , see this question for more C - scanf () vs gets () vs fgets () .


I had a similar problem with your scanf() , and I was in your place, so I wrote down the solution for a while.

+10
source

All Articles