kank
kank

Reputation: 3

Using getchar() to count spaces, tabs, and newlines

I am currently writing a program that takes a sentence entered by the user and counts the number of Spaces, tabs, and newlines in the sentence, and then prints the values.

The input is terminated by a ! or . or ? character.

The problem I have is my program doesn't seem to end when any of the above characters is entered at the end of the input.

Here is the current program:

#include <stdio.h>

int main(void)
{
    int space = 0, tab = 0, newline = 0;
    int sentence;

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

    do{
        sentence = getchar();

        if(sentence == ' '){
            ++space;
        }
        else if(sentence == '\t'){
            ++tab;
        }
        else if(sentence == '\n'){
            ++newline;
        }
    }
    while((sentence != '.')||(sentence != '!')||(sentence != '?'));

    printf("Number of space characters: %d\n", space);
    printf("Number of new line characters: %d\n", newline);
    printf("Number of tabs: %d\n", tab);

    return 0;
}

I am stumped and any help is appreciated.

Upvotes: 0

Views: 3775

Answers (1)

Eternal
Eternal

Reputation: 933

just replace || (or) with && (and) because in your case two of the three conditions will always be true for each and every character that is why while loop goes to infinite.

Upvotes: 2

Related Questions