5

I wasted hours thinking on why is this program working unproperly, without success. It always prints "The character is a special symbol".

#include <stdio.h>
int main( void )
{
    char character;
    printf( "Please type any character and I will tell you what type it is:\n" );
while( 1 )
    {
        scanf( "%c", &character);
        if( character >= 65 && character <= 90 )
            printf( "The character is A-Z\n" );
        else if( character >= 97 && character <= 122 )
            printf( "The character is a-z\n" );
        else if( character >= 48 && character <= 57 )
            printf( "The character is 0-9\n" );
        else if(( character >= 0 && character <= 47 ) ||
                ( character >= 58 && character <= 64 ) ||
                ( character >= 91 && character <= 96 ) ||
                ( character >= 123 && character <= 127 ))
            printf( "The character is a special symbol\n" );
    }
}

RUN EXAMPLE

Please type any character and I will tell you what type it is:
4
The character is 0-9
The character is a special symbol

I've noticed it doesn't happen when I delete the while loop, but I don't understand why, I want that loop.

2
  • don't use scanf with a character instead use fgetc(stdin) Commented Sep 13, 2014 at 1:42
  • Because of the ugly way it works. fgetc(stdin) does not suffer from the leading whitespace characters such as \n. Sure it still gets them, but does no conversions. stackoverflow.com/questions/12063879/… Commented Sep 13, 2014 at 11:19

2 Answers 2

6

Your scanf should be like this:

    scanf(" %c", &character);

You are getting The character is a special symbol because scanf is also reading \n.

Sign up to request clarification or add additional context in comments.

4 Comments

It has to have that space before the %, and it works! But I don't understand how :/ How should I google it? I already tried "[^\n]"
@user3646717: space before % will skip white space and reads the next character that is not white space.
"%d", "%s", "%f", " ", etc. all consume leading white-space. 3 exceptions: "%c", "%[", "%n"
Thank you very much, I didn't know about that leading white-space!
-3

4 meets the condition to printf( "The character is a special symbol\n" );

1 Comment

No no ! It will print The character is 0-9 as ASCII value of 4 is between 48 and 57

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.