简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM