在测试为真条件之后,为什么会执行printf?

5

我是 C 语言的初学者,如果我的问题很蠢或描述不清楚,请多包涵。

我正在阅读 C primer plus,在第八章中有一个例子是一个循环,用于测试用户是否输入了换行符,但我无法理解。

这段代码很短,我会把它展示给你:

int main(void)
{
    int ch; /* character to be printed */
    int rows, cols; /* number of rows and columns */
    printf("Enter a character and two integers:\n");
    while ((ch = getchar()) != '\n')
    {
        if (scanf("%d %d",&rows, &cols) != 2)
            break;
        display(ch, rows, cols);
        while (getchar() != '\n')
            continue;
        printf("Enter another character and two integers;\n");
        printf("Enter a newline to quit.\n");
    }
    printf("Bye.\n");
    return 0;
}
void display(char cr, int lines, int width) // the function to preform the printing of the arguments being passed 

我不明白的是这里:

while (getchar() != '\n')
                continue;
            printf("Enter another character and two integers;\n");
            printf("Enter a newline to quit.\n");

首先,while (getchar() != '\n')是在测试第一个字符是否被输入了? 其次,如果确实是这样,为什么continue没有跳过printf语句并进入第一个while?这不是应该做的吗?
谢谢。

1
我正在阅读《C Primer Plus》。那是你最大的问题!!用火把那本书烧掉!!!现在就动手! - Tony The Lion
3
continue 只是个幌子,最好改为 while (getchar() != '\n'); - Daniel Fischer
非常感谢您,Daniel Fischer。 :) - MNY
1
getchar() != '\n' 读取一个字符,将其与 '\n' 进行比较,如果不是它就被完全丢失了。按照 @TonyTheLion 的建议操作。最好检查一下 http://lysator.liu.se/c,寻找优质的 C 文本。 - vonbrand
4个回答

7

由于while语句后面没有花括号,因此只有紧接着的下一行被包含在循环中。所以,continue会继续执行while循环,直到找到一个新的换行符,然后执行printf语句。

这等同于:

 while (getchar() != '\n')
 {
    continue;
 }

2
+1 是为了帮助询问者找到真正的问题。 - HWende
非常感谢您的回复!但是我认为如果编译器看到getchar()函数,它会停止并要求用户输入一个字符,然后测试它,然后继续...所以while中的getchar()是否在测试先前的输入?@SShaheen - MNY
1
只要输入缓冲区中仍有未使用的输入,getchar() 就会从缓冲区中读取一个字符。通常情况下,来自 stdin 的输入只有在用户按返回/回车键后才会发送到程序中,因此在缓冲区中总是有一个换行符等待 getchar() 读取。如果缓冲区中没有未使用的输入,并且流没有关闭或损坏,getchar() 将一直阻塞,直到有输入传递到缓冲区中为止。 - Daniel Fischer
@DanielFischer 恰好是我需要理解的。你太棒了。 - MNY
@Nir 还要注意的是continue语句会跳过dofor或者while循环中的下一个迭代。因此,如果while语句改成了if语句,程序将按照你原本想的那样运行。 - SShaheen
显示剩余5条评论

1

在两个printf之前应用了continuewhile,因此当您输入\n时,将从最内层的while退出回到该行。

printf("Enter another character and two integers;\n");

0

continue语句作用于最近的while循环中。

while (stuff)
  continue;

是等同于

while (stuf);

(注意分号)。

你只需要说“一直循环,直到条件变为假”。


0

这里的while()循环仅与continue语句相关联。 因此它与printf语句无关..........


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接