TacoCat
TacoCat

Reputation: 469

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?

Upvotes: 1

Views: 1079

Answers (5)

Jobs
Jobs

Reputation: 3377

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.

Upvotes: 1

Colum
Colum

Reputation: 986

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);

Upvotes: 0

damichab
damichab

Reputation: 189

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)

Upvotes: 0

softwarenewbie7331
softwarenewbie7331

Reputation: 967

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] != '?');

Upvotes: 2

William Pursell
William Pursell

Reputation: 212208

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

Upvotes: 0

Related Questions