0

My problem is that the scanf for the character is skipped and it doesn't check scan the char to see if I want to repeat the program again or not so why this is happening?

#include <stdio.h>
#include <stdlib.h>

int main()
{

    int number,check;
    char rep;

    printf("Program to check if number is even or odd");

    while( (rep!='N') || (rep!='n') )
    {
        printf("\n\nPlease enter the number: ");
        scanf("%d",&number);

        check = number%2;

        if(check != 0)
            printf("\nNumber is odd.");
        else
            printf("\nNumber is even.");
        printf("\n");

        printf("Do you want to enter number again?\nY=yes\tN=no\n");
        scanf("%c", &rep);
    }


    return 0;
}
Marievi
  • 4,951
  • 1
  • 16
  • 33
Mina Nagy
  • 41
  • 8
  • 1
    There are hundreds (or maybe even thousands) of duplicates here, but the gist of the problem is that after you read the number, the newline is still in the input buffer. Gues what the next `scanf` call reads... – Some programmer dude Mar 29 '16 at 10:37
  • 1
    and `char rep=0;`... `while(rep!='N' && rep!='n'){` – BLUEPIXY Mar 29 '16 at 10:44

1 Answers1

1

Change scanf("%c", &rep); to scanf(" %c", &rep);.

This is because a '\n' is left in stdin the first time you input a number. When executing scanf("%c", &rep);, that '\n' is immediately consumed by scanf() and assigned to rep. Since '\n' is equal to neither 'N' nor 'n', that loop continues.

With the leading space in the format string, all whitespace characters are discarded before reading starts. In your case, the invisible '\n' will be ignored, so that you can input a character.

Also, you should write char rep = 0; instead, in case the original value of rep happens to be 'n' or 'N'.

nalzok
  • 14,965
  • 21
  • 72
  • 139