-2

I just learned C programming. Now, I am trying to perform looping using the goto control statement, but I just faced a problem when I use variable char.

#include <stdio.h>

char score;
int main(){
    loop:
    printf("Please Input Your Score : ");
    scanf("%c", &score);
    switch(score){
        case 'A' :
          printf("Nilai Anda Baik");
          break;
        default :
          printf("Nilai Anda Salah");
          goto loop;
        }
    return 0;
}

The problem is if I input the wrong score such as 'B', it will print "Nilai Anda Salah" and then automatically print again "Please Input Your Score: Nilai Anda Salah" one time. After that print again "Please Input Your Score: " and then I can input again the score.

I don't know why it is skipping the scanf command.

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 2
    Have you had a look what the value of `score` is that 2nd time? – John3136 Apr 23 '17 at 11:55
  • 5
    "_Im sorry if it is ever being asked, i just cant find the answer_" Clearly you've not researched the problem. Did you take the time to google 'scanf gets skipped' or something like that? – Spikatrix Apr 23 '17 at 11:55
  • 1
    Why are you using `goto`? Also take this opportunity to read the manual page for `scanf` – Ed Heal Apr 23 '17 at 11:57
  • 1
    add a line of getchar() after the scanf or add space to scanf before the %c like so: scanf(" %c", &score); _also_: http://stackoverflow.com/questions/46586/goto-still-considered-harmful – CIsForCookies Apr 23 '17 at 12:00
  • Print `score` after the `default` label: `printf("score is %d\n", score);` – pmg Apr 23 '17 at 12:02
  • 2
    Did you consider printffing out the ASCII value of 'score' each time as a debugging measure, (because you should have done)? That, or learn how to use your debugger ASAP. – ThingyWotsit Apr 23 '17 at 12:06

1 Answers1

1

Use the following format specifier

scanf(" %c", &score);
      ^^^

to skip the new line characters between entered characters.

Also according to the C Standard function main without parameters shall be declared like

int main( void )

Take into account that it is a bad idea to use the goto statement. Also there is no need to declare the variable score as global.

The program can look the following way

#include <stdio.h>

int main(void) 
{
    char score = 'A';

    do
    {
        printf( "Please Input Your Score : " );
        scanf( " %c", &score );

        switch( score )
        {
        case 'A' :
            puts( "Nilai Anda Baik" );
            break;
        default :
            puts( "Nilai Anda Salah" );
            break;
        }
    } while ( score != 'A' );

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335