-3

This program doesn't seem to accept input at every iteration of the while loop, when ideally it should.However when I replace the %c parameter of the scanf() function with %d ( i.e an integer input rather than a char input) it seems to just work absolutely fine, which input accepted for every iteration of the while loop. Why do I see this discrepancy ?

int main()
{
    char grade;
    int i=0;

    while(i<10){
        printf("Enter ur grade\n");
        scanf("%c", &grade);
        switch(grade){
            case 'A' : printf("U R THE BEST\n");
                       break;
            case 'B' : printf("U R VERY GOOD DUDE...\n");
                       break;
            case 'C' : printf("U R GOOD DUDE...\n");
                       break;
            case 'D' : printf("U R Not good DUDE...\n");
                       break;
            case 'E' : printf("U R WORST DUDE...\n");
                       break;
            default  : printf("U r AWESOME...\n");
                       break;
        }
    i++;
}
Miss J.
  • 351
  • 1
  • 5
  • 15
  • 1
    Can you give an example of the input and the output you get? – DJ Burb Oct 01 '14 at 16:06
  • 3
    scanf doesn't remove newline from input buffer. many dups on SO: http://stackoverflow.com/questions/13275417/why-scanfd-does-not-consume-n-while-scanfc-does (not really dupe but solution to your problem) – Adriano Repetti Oct 01 '14 at 16:07
  • Every time you input a char (you are actually inputting two chars), there's a newline (`\n`) char left in the input stream, which is consumed in the next iteration. You need to clear it with `getchar()` or similar techniques. – P.P Oct 01 '14 at 16:07
  • add fflush(stdin); after scanf – Satya Oct 01 '14 at 16:11
  • Your braces don't balance. Also what's wrong with `for(int i = 0; i < 10; ++i)`? – Bathsheba Oct 01 '14 at 16:13

2 Answers2

-1

Add a space before the %c of the scanf. This is done to remove all blanks from the stdin before scanning a character. scanf does not take the \n(enter key) character after entering a character and leaves it in the buffer which is taken when scanf is called again.

Another thing: you forgot to put one } in your code.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
-1

try this : put a space before %c it is because it stores \n too.

 scanf(" %c", &grade);
Rustam
  • 6,485
  • 1
  • 25
  • 25