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

MNY*_*MNY 5 c

我是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 
Run Code Online (Sandbox Code Playgroud)

我不明白的是这里:

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

首先,while (getchar() != '\n')是测试第一个ch进入了吗?第二,如果这是真的,那么为什么继续不是擦除printf语句并转到第一次呢?这不是应该做的吗?

TNX

SSh*_*een 7

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

它相当于:

 while (getchar() != '\n')
 {
    continue;
 }
Run Code Online (Sandbox Code Playgroud)

  • +1来获取这里询问人的真实问题. (2认同)