简体   繁体   中英

While loop with “if” doesn't work properly

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.

Your scanf should be like this:

    scanf(" %c", &character);

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

4满足printf的条件(“字符是特殊符号\\ n”);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM