gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 14:57:38 27 4
gpt4 key购买 nike

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

我正在阅读 C primer plus第 8 章 中的示例之一是测试用户是否输入的某个循环 - a是否换行符 ,我无法理解。

代码很短,所以我会展示给你看:

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') 正在测试是否输入了第一个 ch,对吧?其次,如果那是真的,为什么 continue 不跳过 printf 语句并转到第一个 while?这不是它应该做的吗?

谢谢

最佳答案

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

等同于:

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

关于c - 为什么在测试真实条件后执行 printf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14626940/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com