为什么是“if(c != ' ' || c != ' ')" 在不应该的时候激活?

问题描述 投票:0回答:1

我的程序计算单词数、字符数和行数。

输入示例:

b

预期输出:

4,2,2

注意,我输入

b
,然后按Enter,然后再次输入
b
,之后,我按Enter,再按Ctrl+D,就会出现打印语句。

问题是我得到:

4,3,2

我知道问题是因为我的 if 语句正在激活,但是当我在脑海中运行这个程序时,我根本不明白为什么它应该被激活。

#include <stdio.h>
#include <string.h>

int main()
{
    int traversal = 1;
    unsigned long int charcount = 0;
    unsigned long int wordcount = 0;
    unsigned long  int linecount = 0;
    int counter = 0;
    char c;
    while ((c = getchar()) != EOF)
    {
        charcount = charcount +1;

        if((c <= 'z' && c >= 'a') || (c <= 'Z' && c >= 'A') || c == '\'')
        {

            if (counter >= 1)
            {
                wordcount++;
                counter = 0;
                printf("counter\n");
            }       
        }
        else
        {
            if (c != ' ' || c != '\n')  //** This should only run if we get NO letter
            {
                counter++;
            }
        }
        if (c == '\n')
        {
            linecount = linecount+1;
            wordcount = wordcount+1;
            traversal = traversal +1;
            printf("%lu\n", wordcount);
        }
        if(c == ' ')
        {
            wordcount = wordcount+1;
        }    
    }
    printf( "%lu %lu %lu\n", charcount, wordcount, linecount );
}

我确信我所做的

if
语句当时只激活
c
不是换行符(输入),或者如果它是空格。为什么它在运行?我该如何解决它?

c if-statement
1个回答
4
投票

让我们看看您的条件:

if (c != ' ' || c != '\n')  //** This should only run if we get NO letter

我们来看三个案例:

  1. 如果
    c == ' '
    ,那么我们有
    (false || true)
    ,即
    true
  2. 如果
    c == '\n'
    ,那么我们有
    (true || false)
    ,即
    true
  3. 如果
    c == 'a'
    ,那么我们有
    (true || true)
    ,即
    true

你实际上想要:

if (c != ' ' && c != '\n')

这意味着当

c
既不是空格也不是换行符时,我们将执行条件语句。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.