0

The program takes two inputs and if the result is N then it goes through the while loop until the user types N five times. If Y is pressed then it exits the loop.

This while loop executes perfectly if the input is Y, however, if the input is N, it executes properly the first time it runs but the second time it executes line 13 twice before moving on. It seems to miss getting an input the second time, but then it fixes after returning, thus the result is shown as:

result when the program runs

Here is my code:

// Preprocessor commands
#include <stdio.h>
#include <stdlib.h>
//-----------------------------

int main(){ 
    int attempts=0;
    char result;

    while(attempts < 5){
        printf("\n");
        printf("Entered Loop\n");
        printf("Enter result (P/F)\n");
        scanf("%c", &result);
        if(result == 'P'){
            printf("Passed\n");
            attempts++;
            break;
        }
        else if(result == 'F'){
            printf("Entered F Loop\n");
            printf("Try again\n");
            attempts++;
            continue;
        }
        printf("Exited F Loop\n");
    }

    if(attempts == 5){
        printf("QUIT!\n");
    }
}
Bob Jane
  • 57
  • 6
  • 1
    `scanf(" %c", &result);` - mind the space between the first `"` and `%`. – woz Jul 11 '17 at 13:56
  • Thank you. That seems to have worked.How come that's needed ? It usually works without it from my little experience. – Bob Jane Jul 11 '17 at 13:59
  • [Read this question](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer). You'll find the answers on the accepted answer :) – woz Jul 11 '17 at 14:01
  • oh yes, that's perfect. Thanks – Bob Jane Jul 11 '17 at 14:05

0 Answers0