-1
> #include <stdio.h>

int main(void)
{
    char a;
    printf("Enter a capital alphabet: ");
    do{
    scanf("%c", &a); }
    while(a>=65 && a<=90);
}

I am building a program which only takes one uppercase letter as input. But it doesn't prompt to input again, even if I input a lowercase letter, a number, or a symbol.

Where am I going wrong in this?

brownputin
  • 79
  • 5

2 Answers2

2
  • Add a whitespace character before %c to have it skip newline character (from hitting Enter)
  • Negate the loop condition to read again if the input is out of desired range.
  • Use character literals for better understanding.
  • Use isupper() for even better understanding.

Manual comparision version:

#include <stdio.h>

int main(void)
{
    char a;
    printf("Enter a capital alphabet: ");
    do{
    scanf(" %c", &a); }
    while(!(a>='A' && a<='Z'));
}

isupper() version:

#include <stdio.h>
#include <ctype.h>

int main(void)
{
    char a;
    printf("Enter a capital alphabet: ");
    do{
    scanf(" %c", &a); }
    while(!isupper((unsigned char)a)); /* case to unsigned char to avoid trouble when a is negative */
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
2
#include <stdio.h>

int main(void)
{
    char a;  
    do{
        printf("Enter a capital alphabet: "); // printf should be in while loop to print the request when you did not enter a capital alphabet.
        scanf(" %c", &a);  // add space character before %c

    } while(a <='A' || a >= 'Z'); // it's more clear when you use 'A' and 'Z' in stead of 65 and 90.
}

See scanf() leaves the new line char in the buffer

and While-loop ignores scanf the second time

Hitokiri
  • 3,607
  • 1
  • 9
  • 29