gpt4 book ai didi

c - printf 和 scanf 如何循环工作?为什么我在 scanf 中不需要\n?

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:29 25 4
gpt4 key购买 nike

我真的不明白下面的代码。它是如何工作的(我的意思是 I/O 缓冲区)。我的代码中不需要 \n 字符,它仍然有效!任何人都可以逐步向我解释吗?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
int x = -1;

do
{
printf("Give x: ");
scanf("%d", &x);
}while(x<=0);

printf("x = %d\n", x);

x = -1;

while(x<=0)
{
printf("Give x: ");
scanf("%d", &x);
}

printf("x = %d\n", x);

return 0;
}

最佳答案

根据 scanf's documentation on cplusplus.com :

Whitespace character: the function will read and ignore any whitespace characters
encountered before the next non-whitespace character (whitespace characters include
spaces, newline and tab characters -- see isspace). A single whitespace in the format
string validates any quantity of whitespace characters extracted from the stream
including none).

这就是为什么您不需要在 scanf 中指定 \n 的原因,下一个 scanf 调用将忽略它。

关于c - printf 和 scanf 如何循环工作?为什么我在 scanf 中不需要\n?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20057355/

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