我是 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
?这不是应该做的吗?谢谢。
continue
只是个幌子,最好改为while (getchar() != '\n');
。 - Daniel Fischergetchar() != '\n'
读取一个字符,将其与'\n'
进行比较,如果不是它就被完全丢失了。按照 @TonyTheLion 的建议操作。最好检查一下 http://lysator.liu.se/c,寻找优质的 C 文本。 - vonbrand