计算换行符、空格和制表符 [英] counting newlines, spaces, and tabs

查看:49
本文介绍了计算换行符、空格和制表符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题来自 K&R p.20:编写一个程序来计算空格、制表符和换行符.

This problem is from K&R p. 20: Write a program to count blanks, tabs, and newlines.

这是我的尝试:

#include <stdio.h>

int main()
{
  int character, whitespace = 0;

  printf("Enter some text, and press Ctrl-d when you're done.\n\n");

  while((character = getchar() != EOF) {
    if(character == (' ' || '\n' || '\t')) {
      ++whitespace;
    }
  }

  printf("\nYour text contains %d spaces, tabs, and lines.\n", whitespace);

  return 0;
}

该程序不起作用.无论用户文本包含多少空格、制表符和换行符,它始终给出答案 0.任何人都可以看到问题吗?还有一件奇怪的事情:我必须按 Ctrl-d 两次才能注册.我不知道为什么.谢谢!

The program doesn't work. It always gives the answer 0 no matter how many spaces, tabs, and newlines the user text contains. Can anyone see the problem? There's one other strange thing: I have to press Ctrl-d twice for it to register. I have no idea why. Thanks!

推荐答案

if(character == (' ' || '\n' || '\t'))

测试character是否等于(' ' || '\n' || '\t')的结果(结果为1,表示 || 的结果为真).您需要针对三个可能的值中的每一个单独测试它,例如,

tests whether character is equal to the result of (' ' || '\n' || '\t') (the result of this is 1, indicating that the result of the || is true). You need to test it individually against each of the three possible values, e.g.,

if(character == ' ' || character == '\n' || character == '\t')

这篇关于计算换行符、空格和制表符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆