Search code examples
cinputfgetsfgetc

Detect white space in the input


I want to make a program that only accepts lowercase characters from the user. And I want it to print an error whenever there is a whitespace, a capital letter in the input or any character beside the alphabet.

But my code is behaving in an unexpected manner, I'm not sure why. The error message is printed only if a whitespace or a capital letter was the first character that was entered in the input. How is it possible even though I am scanning the whole string with fgetc looking for a whitespace?

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

int main ( void )
{
    char buff[BUFSIZ];
    char ch = fgetc(stdin);
    if  (fgets( buff, sizeof buff, stdin ) != NULL && islower(ch)) {
        while (ch != ' ' && ch != EOF)
        {
            printf("There are No Spaces in the input!\n");
            return 0;
        }
    }
    printf("Error\n");
}

Solution

  • You're not scanning the whole string. You're getting the first character into ch, then you're getting the rest of the line into buff (more or less), and then if ch was a lower-case character, your program will print "There are no spaces" over and over because you never again change ch.