Reputation: 1051
I am a beginner, just learning C; so, please be patient with me.
I am trying to write a very simple program that goes through a string, counts the characters in each word, and then replaces those words with the number of their characters. My problem is that I am stuck in an infinite loop and cannot figure out why! Here is the code:
#define NEWLINE '\n'
#define SPACE ' '
int main(int argc, char *argv[]) {
int character;
int count = 0;
printf("\nType in a sentence of any lenght, then hit ENTER!\n");
character = getchar();
while (character != NEWLINE) {
while ((character != SPACE) || (character != NEWLINE)) {
count++;
character = getchar();
}
printf("%d ", count);
count = 0;
if (character != NEWLINE) {
character = getchar();
}
}
printf("\n");
system("PAUSE");
return 0;
}
Thanks for everyone who helped me! I guess I go back and study logical operators a bit more.
Upvotes: 2
Views: 1220
Reputation: 3381
Replace the || (OR) with && (AND) because the while loop will always be true and for that reason it will never break out of the loop. It should work if you replace it.
Upvotes: 1
Reputation: 1034
You have an always true condition:
(character != SPACE) || (character != NEWLINE)
eg:
character = ' ': false or true => true
character = '\n': true or false => true
You should change it to:
(character != SPACE) && (character != NEWLINE)
That should fix your infinite loop.
Upvotes: 4
Reputation: 152566
while ((character != SPACE) || (character != NEWLINE)) {
count++;
character = getchar();
}
this will loop infinitely because the inverse:
(character == SPACE) && (character == NEWLINE)
will ALWAYS be false.
I suspect you mean
while ((character != SPACE) && (character != NEWLINE)) {
count++;
character = getchar();
}
Upvotes: 15