Gergely Kovacs
Gergely Kovacs

Reputation: 1051

Logical Error in my C Code

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

Answers (4)

SomeWittyUsername
SomeWittyUsername

Reputation: 18358

Replace the || With &&

Upvotes: 2

Force444
Force444

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

Michael McGuire
Michael McGuire

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

D Stanley
D Stanley

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

Related Questions