gpt4 book ai didi

c - 在 C 中验证用户输入

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:46 24 4
gpt4 key购买 nike

所以我需要用户输入一个大于 2 的整数。

    printf("Number of triangles (must be greater than 2) = ");
fflush(stdin);
scanf("%d", &num_of_triangles);
while (num_of_triangles < 3) // ?how to check using scanf?
{
printf("Number of triangles (must be greater than 2) = ");
fflush(stdin);
scanf("%d", &num_of_triangles);
}

是否有可能针对重复行优化此代码?

最佳答案

代替while,使用do...while。这样,循环将始终至少运行一次。

num_of_triangles = 0;
do {
printf("Number of triangles (must be greater than 2) = ");
scanf("%d", &num_of_triangles);
while (getchar() != '\n'); // this flushes the input buffer
} while (num_of_triangles < 3);

另外,不要 fflush(stdin),因为那是未定义的行为。

编辑:

似乎 Visual Studio 允许 fflush(stdin)。来自 MSDN :

The fflush function flushes a stream. If the file associated with stream is open for output, fflush writes to that file the contents of the buffer associated with the stream. If the stream is open for input, fflush clears the contents of the buffer. fflush negates the effect of any prior call to ungetc against stream. Also, fflush(NULL) flushes all streams opened for output. The stream remains open after the call. fflush has no effect on an unbuffered stream.

但一般而言,不应依赖此行为。像上面的代码那样做一些更可移植的东西是更可取的。

关于c - 在 C 中验证用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33301698/

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