Search code examples
ccharscanfgetchar

Does if-structure in C affect the value of variable?


Im trying to write a simple C program to convert the cases of letters

char a;
a = getchar();
if(a<=90&&a>=65)
    putchar(a+32);
else if(a<=122&&a>=97)
    putchar(a-32);
else
    putchar(a);

When the input is 'A' or 'c',the output is correct;however,when it comes to 'g',the output becomes space and when entering numbers and signals,only get a different output instead of itself.Then I changed the order of ifs,the second problem was solved but the 'g' problem remains.

But I thought the if-structure wouldnt change the value of a;Im quite confused and wonder how.


Solution

  • The function getchar reads all symbols including white spaces from the input stream.

    Use instead

    scanf( " %c", &a );
    

    Also it is a bad idea to use magic numbers like for example 65 or 32.

    Here is a demonstrative program

    #include <stdio.h>
    
    int main(void) 
    {
        char c;
    
        while ( scanf( " %c", &c ) == 1 )
        {
            if ( 'A' <= c && c <= 'Z' )
            {
                putchar( c | ' ' );
            }
            else if ( 'a' <= c && c <= 'z' )
            {
                putchar( c & ~' ' );
            }
            else
            {
                putchar( c );
            }
        }
    
        return 0;
    }
    

    If to enter for example

    A
    a
    1
    G
    g
    2
    

    then the program output will be

    aA1gG2
    

    If to use getchar then the approach can look the following way

    #include <stdio.h>
    #include <ctype.h>
    
    int main(void) 
    {
        int c;
    
        while ( ( c = getchar() ) != EOF )
        {
            if ( 'A' <= c && c <= 'Z' )
            {
                putchar( c | ' ' );
            }
            else if ( 'a' <= c && c <= 'z' )
            {
                putchar( c & ~' ' );
            }
            else if ( isgraph( ( unsigned char )c ) )
            {
                putchar( c );
            }
        }
    
        return 0;
    }