c为什么在测试真实条件后执行 printf

  • 本文关键字:条件 执行 printf 真实 测试
  • 更新时间 :
  • 英文 :


我是C语言的初学者,所以如果这个问题很愚蠢或问得很奇怪,请原谅我。

我正在阅读 C primer plus,第 8 章中的示例之一是测试用户是否输入 - a newline character or not 的循环,我无法理解。

代码很短,所以我会告诉你:

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')正在测试第一个通道输入正确吗?其次,如果这是真的,为什么继续不跳过printf语句并转到第一个?这不是它应该做的吗?

因为 while 语句后面没有大括号,所以循环中只包含下一行。因此,continue继续 while 循环,直到找到换行符,然后继续执行 printf 语句。

它相当于这个:

 while (getchar() != 'n')
 {
    continue;
 }
继续应用于

两个printf -s 之前的while,因此当您进入 n 时,您将从最里面出来,同时回到行

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

continue适用于最近的while循环。

while (stuff)
  continue;

while (stuf);

(注意分号)。

你只是说"继续循环,直到条件变得错误"。

这里的 while() 循环仅与 continue 语句相关联。所以它与 printf 语句没有关系......

最新更新