0

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;
2
  • 4
    Hint: look at the condition (user_input != '.') || (user_input != '?') || (user_input != '!'). Commented Mar 6, 2017 at 21:12
  • 6
    Note that you're using spaces, tabs, and new_lines without initializing them. They can contain any garbage. Number of space characters: 223723574Number of new line characters: 32767Number of tabs: 1419576536. Turn on warnings, starting with -Wall. Commented Mar 6, 2017 at 21:20

1 Answer 1

7
(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 != '!')
Sign up to request clarification or add additional context in comments.

1 Comment

Yes that is what I want to do. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.