为什么不能使用多个" if" s但它确实可以使用"如果" s"否则如果" s在while循环中?

时间:2018-01-30 19:21:22

标签: c if-statement while-loop getchar

这是我的代码而不使用 else if

inputString.replace(/.{1}/ ,inputString.charAt(0).toUpperCase())

这是使用 else的代码,如果

#include <stdio.h>

main()
{
    long s = 0, t = 0, n = 0;
    int c;
    while ((c = getchar()) != EOF)
        if (c == ' ')
            ++s;
        if (c == '\t')
            ++t;
        if (c == '\n')
            ++n;
    printf("spaces: %d tabulations: %d newlines: %d", s, t, n);
}

出于某种原因,如果不使用,则不起作用。是什么原因?我知道使用如果一个接一个地使用 else,如果在第一个语句为true时停止。这在性能上有所不同。无论如何不使用 else if 在这个特定的(如果不是其他的)while循环中似乎没有用。

感谢。

3 个答案:

答案 0 :(得分:7)

正确缩进,您的第一个程序如下所示:

#include <stdio.h>

main()
{
    long s = 0, t = 0, n = 0;
    int c;
    while ((c = getchar()) != EOF)
        if (c == ' ')
            ++s;
    if (c == '\t')
        ++t;
    if (c == '\n')
        ++n;
    printf("spaces: %d tabulations: %d newlines: %d", s, t, n);
}

while循环的主体是单个陈述。

if ... else if ... else if ... else都形成了一个重要的声明。通过将您的条件分成几个语句(ififif),除了第一个语句之外,您已经移动了所有语句。

要避免此问题,请始终使用复合语句(即块{ ... })作为whileif语句的正文。

顺便说一句,main()自1999年以来一直没有效。它应该是int main(void)

答案 1 :(得分:1)

来自standard(仅选择了语法规则的相关部分)

   iteration-statement: while ( expression ) statement

   statement: selection-statement

   selection-statement:
             if ( expression ) statement
             if ( expression ) statement else statement

您正在编写一个迭代语句 - 由while(expression)和单个语句组成。在您的情况下,该声明是一个选择声明 - 现在检查它。除非你使用else ifelse,否则它不是单个语句 - 而是除了while语句中的所有语句之外的所有语句的多个语句,其余的都在它之外。

您的代码基本上就是这个

  while ((c = getchar()) != EOF){ <--- the selection statement
    if (c == ' ')
        ++s;
  }<-- 
  if (c == '\t')
        ++t;
  if (c == '\n')
        ++n;

在方块和缩进中放置括号可以避免这种错误。

答案 2 :(得分:1)

因为你忘记了while周围的大括号,所以它只遍历第一个if语句,然后退出循环并评估其他两个if语句。

另外,为什么不使用switch声明?

while ((c = getchar()) != EOF) {
    switch(c) {
       case ' ':
          ++s;
          break; 
       case  '\t':
          ++t;
          break;
       case '\n':
          ++n;
          break;
    }
}
printf("spaces: %d tabulations: %d newlines: %d", s, t, n);