为什么使用多个"if"不起作用,但它确实可以在while循环中使用"if"和"else if"?

Phi*_*oll 1 c if-statement while-loop getchar

这是我的代码,不使用else if:

#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);
}
Run Code Online (Sandbox Code Playgroud)

这是使用else的代码,如果:

#include <stdio.h>

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

出于某种原因,不使用else如果不起作用.是什么原因?我知道,使用,如果确实是一个接一个,而使用否则,如果在情况属实的第一条语句停止.这在性能上有所不同.无论如何不使用else,如果在这个特定的(如果不是其他)while循环似乎不起作用.

谢谢.

mel*_*ene 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);
}
Run Code Online (Sandbox Code Playgroud)

while循环体是单个语句.

if ... else if ... else if ... else一切形成一个大的声明.通过分离条件为若干语句(if,if,if),你感动了所有,但第一个跳出while循环的.

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

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