Telefang
Telefang

Reputation: 133

While loop with multiple conditions in C

I'm trying to read a character that has to be 'C' or 'n'.
In case it is not, print an error and ask for another char.

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int c;
    printf("Enter the character: ");

    c = getchar();

    while (!(c=='C' && c=='n')){
            printf("Wrong!.\n");
            printf("Enter the character: ");
            c = getchar();  
    }

    printf("\n");
    return 0;
}

And what I get is:

Enter the character: s
Wrong!
Enter the character: Wrong!
Enter the character:

Like it is checking twice in the while loop.

Upvotes: 0

Views: 1150

Answers (2)

Steve
Steve

Reputation: 633

getchar() is used for character by character input control. You could still use getchar(), but you have to handle all the characters from the keyboard. You can do this by ignoring the characters you do not care about.

I would also restructure your loop do be a do-while loop instead of a while loop

To modify your code to trap for upper and lower case A-Z you can do the following:

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int c;
    printf("Enter the character: ");

    do {
        c = getchar(); 

        // ignore non a-z or non A-Z
        if( c < 'A' || ( c >'Z' && c < 'a' ) || c > 'z' ) {
            continue;
        }

        // look for the characters you care about
        if( c=='C' || c=='n') {
             break;
        }

        // now we only have incorrect characters that are 
        // only upper or lower case
            
        printf("%c Wrong!\n", (char)c );
        printf("Enter the character: ");

    } while (1);

    printf("\n");
    return 0;
}

Although I have not tested this... You should get something like:

Enter the character: s Wrong!

Enter the character: t Wrong!

Enter the character: C

When you enter "s-=+t\n01234C" .

Note: '\n' I am using to denote a carriage return entered from the keyboard

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182753

Two things:

1) You are pressing a character and then hitting enter. That's two characters. If you want to read a whole line, don't use getchar.

2) Your conditional makes no sense. It will never be the case that c is both equivalent to 'C' and equivalent to 'n', so you're testing something that cannot be. Your loop will never end.

Upvotes: 3

Related Questions