Alamgir Hossain
Alamgir Hossain

Reputation: 31

How can we ignore the enter button press as a character in c programming at the time of taking input from user?

Look at the example:

#include<stdio.h>
int main()
{
    char ch;
    while(scanf("%c", &ch))
    {
        if(ch == 'a' || ch == 'e' || ch == 'i' ||
                ch == 'o' || ch == 'u' || ch == 'A' ||
                ch == 'E' || ch == 'I' || ch == 'O' ||
                ch == 'U')
        {
            printf("It's Vowel\n");
        }
        else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
        {
            printf("It's Consonant\n");
        }
        else
        {
            printf("Wrong Input/ It's not Alphabet\n");
        }
    }
    return 0;
}

After compiling this example code, when I enter 'a', The output is "It's Vowel" and "Wrong Input/ It's not Alphabet". I think the cause for this output is, the compiler takes the character also takes the enter press as a character.

Is there any way to solve this problem?

Upvotes: 1

Views: 962

Answers (1)

I think the cause for this output is, the compiler takes the character also takes the enter press as a character.

It's not the compiler who takes characters. Getting input is a run-time operation. When the program is already running, the work of the compiler is far done, but beside that your guess is correct. It is because scanf() doesn't consume the newline character with made by the press to Enter at the first step.

This newline character then get read at the next iteration by scanf("%c", &ch)) and as the newline character is a legit character it is stored inside of ch.

Is there any way to solve this problem?

Use

while(scanf(" %c", &ch))

instead of

while(scanf("%c", &ch))

Notice the white space character (' ') before %c. This will fetch the abandoned newline character left in stdin from the last iteration.

Upvotes: 1

Related Questions