2

I'm coding on Visual Studio 2015. When I execute below C program, during the execution program skips else part's character scanf function and displays "You entered an invalid character." directly. What is the problem?

    double grade1, grade2, avarage;
    char yes_no;            //character variable for (Y/N) statement
    int std;            //index for students
    int std_num;        //number of students
    printf("Enter how many students will be determined: ");
    scanf("%d", &std_num);
    for (std = 1; std <= std_num; std++);       //loop statement
    {//curly brace for loop

        printf("Enter two grades: ");       //display for inputs
        scanf("%lf %lf", &grade1, &grade2);     //input statement

        avarage = (grade1 + grade2) / 2;

        if (avarage >= 50)
            printf("Successful.\n");
        else
        {
            printf("Did the student take this exam before?(Y/N): ");
            scanf("%c", &yes_no);

            if (yes_no == 'Y' || yes_no == 'y')
                printf("Unsuccessful, and has no other chance.\n");
            else if (yes_no == 'N' || yes_no == 'n')
                printf("Unsuccessful, but has one more chance.\n");
            else
                printf("You entered an invalid character.\n");
        }
    }//curly brace for end of the loop
return 0;
}
ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • 1
    What's the betting that this is going to be 'line feed left in input buffer' #005694597 ? – Martin James Feb 27 '16 at 21:57
  • 1
    `scanf("%c", &yes_no);` --> `scanf(" %c", &yes_no);` – BLUEPIXY Feb 27 '16 at 21:59
  • Thank you very much, I did not know this before :) – Berat Postalcioglu Feb 27 '16 at 22:03
  • Actually the problem is elsewhere: commenting `{//curly brace for loop` does not make it the `for` block! you have a spurious `;` at the end of the `for` statement line. The body of your `for` statement is empty. The block is a separate statement that is executed once in all cases. Use a different brace style: put the opening brace on the same line as the `for`, `while`, `if` or `switch statement, and the closing brace on a line of its own. This is known as the K&R style, from the names of the language authors: Kernighan and Ritchie. – chqrlie Feb 27 '16 at 22:11
  • This question is indeed a duplicate, but it has another important bug. – chqrlie Feb 27 '16 at 22:12
  • Well, at least I didn't bet any actual cash.. ;) – Martin James Feb 27 '16 at 22:13
  • @chqrlie I noticed that you mentioned and fixed these bugs. Thank you for your suggestions, I note down these.. – Berat Postalcioglu Feb 27 '16 at 22:22

0 Answers0