tgaskey
tgaskey

Reputation: 23

C - While loop not exiting how expected with string input

I want to exit my do-while loop when the user enters "exit" from the command line. I'm trying to do it without using strcmp() but it's just not performing how I think it should. When testing it if the user enters e for the first character, or x for the second character, or i for the third, or t for the fourth character then the program exits. It's probably something simple that I'm missing. So can anyone explain why this isn't working how I'm expecting? Thanks.

#include <stdio.h>

#define FLUSH while(getchar() != '\n');

int main(){
    char input[20] = {0};

    printf("This is a string math program. Enter a string 9 characters or less"
                " followed by an operater and finally another string 9 characters or less."
                " There should be no spaces entered. To exit the program type exit.\n");

    do{
        printf("Input: ");
        scanf("%s",input);

        FLUSH



    } while((input[0] != 'e') && (input[1] != 'x') && (input[2] != 'i') && (input[3] != 't'));
}

Upvotes: 0

Views: 1076

Answers (1)

John Zwinck
John Zwinck

Reputation: 249153

Let's talk about De Morgan's Law. This:

(input[0] != 'e') && (input[1] != 'x') && (input[2] != 'i') && (input[3] != 't')

is required to be true for your loop to continue. It is equivalent to this:

!(input[0] == 'e' || input[1] == 'x' || input[2] == 'i' || input[3] == 't')

So yes, your loop will stop when any character matches. Just use strcmp, but if you can't for some bizarre reason, just change the above logic.

Upvotes: 1

Related Questions