LinhSaysHi
LinhSaysHi

Reputation: 642

Unexpected input when using getchar()

I am creating a program that returns true if a character I input is an upper case letter and the loop stops when I input the char '0'. The code is as follows:

#include <stdio.h>

int main (void)
{
    char c;
    do 
    {
        printf ("Please enter character to check if uppercase: ");
        c = getchar ();

        if ( (c >= 'A') && (c <= 'Z') )
        {
            printf ("true\n");
        }
        else
        {
            printf ("false\n");
        }
    } while ( c != '0');


    return 0;
}

However, I get weird behavior (Output):

Please enter character to check if uppercase: a

false

Please enter character to check if uppercase: false

Please enter character to check if uppercase: b

false

Please enter character to check if uppercase: false

Please enter character to check if uppercase: A

true

Please enter character to check if uppercase: false

Please enter character to check if uppercase: 0

false

- The "false" thats comes after the prompt is not what I typed. For example:

So it seems that getchar() is taking input that is not coming from me. Any ideas?

Upvotes: 0

Views: 629

Answers (2)

P.P
P.P

Reputation: 121427

getchar() leaves a newline character which is consumed in the next iteration. Add another getchar() to ignore the newline:

c = getchar ();
getchar(); // To consume the newline

Or read out all the until newline:

int c=0;
while ((c = getchar()) != '\n' && c != EOF) ;

Upvotes: 2

Henrik
Henrik

Reputation: 4314

You are not handling newlines.

See this answer for clarification.

Upvotes: 2

Related Questions