简体   繁体   中英

Why does the while loop keeps running after I entered the termination parameters?

Why doesn't the while loop break after I enter the symbols that should terminate the loop. (C)

 printf("Enter a sentence: ");
do
{
    message[i] = getchar();
    i++;
}while(message[i - 1] != '.' || message[i - 1] != '!' || message[i - 1] != '?');

if I put . ? or ! at the end it just keeps running. Whats wrong?

the condition for your while loop is trivially true since the character cannot be all three at once.. what you're looking for is

printf("Enter a sentence: ");
do
{
    message[i] = getchar();
    i++;
}while(message[i - 1] != '.' && message[i - 1] != '!' && message[i - 1] != '?');

Change the or's to and's in your while statement.

For "or", as long as there is a "True", the whole statement evaluates to True. Therefore your original 'while' condition always evaluates to "True".

'While' only terminates when the condition evaluates to False. However, in your original condition, that will never happen because:

  1. All three conditions cannot happen(be False) at the same time. The value cannot be '.', '!', and '?' at the same time.

  2. This means: At least two of your three conditions always evaluate to True. Consequently, the 'while' will never evaluate to False, because any permutation of True||False||False will evaluate to True.

If you are entering this interactively, message[ i - 1 ] is almost certainly \\n . Check the value of message[ i - 2 ]

try this:

printf("Enter a sentence: ");
int run = 1;
do {
    message[i] = getchar();
    i++;
    if(getchar() != '!' && getchar() != '?' && getchar() != '.'){
       run = 1;
    } else {
       run = 0;
    }
}while(run == 1);

or , i think this might work :/

printf("Enter a sentence: ");
int run = 1;
do {
    message[i] = getchar();
    i++;
    if(getchar() == '!' || getchar() == '?' || getchar() == '.'){
       break;
    }
}while(run == 1);

You need to swap your OR's with ANDS's.

Whilst message[i - 1] is equal to '.' that period is not equal to '!' and '?', hence your loop will always be true.

try something like...

}while(message[i - 1] != '.' && message[i - 1] != '!' && message[i - 1] != '?');

(untested code off the top of my head)

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