简体   繁体   English

使用getchar()计算空格,制表符和换行符

[英]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. (或)与&&(和),因为在您的情况下,对于每个字符,三个条件中的两个始终为真,这就是while循环变为无限的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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