S. Thomas
S. Thomas

Reputation: 33

do while loop that doesn't end in C

In this program I am attempting to save each character that the user inputs into a do while loop that should count the number of spaces, new lines, and tabs.

When I run my program it doesn't end when '.', '!', or '?'

Why?

int characters, spaces, new_lines, tabs;
int user_input;

printf("Enter a sentence (end by '.' or '?' or '!'):");



do{
user_input = getchar();
 if (user_input == ' ')
    spaces++;
 if (user_input == '\t')
    tabs++;
 if (user_input == '\n')
    new_lines++;

} while((user_input != '.') || (user_input != '?') || (user_input != '!'));

 printf("Number of space characters: %d", spaces);
 printf("Number of new line characters: %d", new_lines);
 printf("Number of tabs: %d", tabs);

 return 0;

Upvotes: 0

Views: 91

Answers (1)

(user_input != '.') || (user_input != '?') || (user_input != '!')

The above doesn't evaluate the way you think it does. For the condition to be false (and the loop to stop) all three clauses must be false. That means that all respective inverses must be true, i.e:

(user_input == '.') && (user_input == '?') && (user_input == '!')

And that is of course impossible. A single character variable cannot contain three different values at once.

I assume you want the loop to terminate if the program receives either of those characters as input, so you need to check that the input is neither of those, meaning:

(user_input != '.') && (user_input != '?') && (user_input != '!')

Upvotes: 7

Related Questions