[英]Validating user input in C
所以我需要一个大于2的int的用户输入。
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
, 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 :
fflush函数刷新流。 如果打开了与流关联的文件以供输出,则fflush将与流关联的缓冲区的内容写入该文件。 如果打开流供输入,则fflush清除缓冲区的内容。 fflush取消了针对流的ungetc之前调用的影响。 同样,fflush(NULL)刷新所有打开的流以供输出。 通话后,流保持打开状态。 fflush对未缓冲的流没有影响。
但是,一般而言,不应依赖此行为。 最好像上面的代码那样做一些更可移植的操作。
fflush(stdin)
是未定义的行为,因此您需要将其完全删除并替换其他内容。
您还应该检查scanf
的输出,以防失败。
如果要提高可读性,也可以将scanf
直接移到while循环中,如下所示
while (scanf("%d",&num_of_triangles)==1 && num_of_triangles < 3)
您可以这样编写代码-
printf("Number of triangles (must be greater than 2) = ");
while (scanf("%d",&num_of_triangles)==1 && num_of_triangles < 3) //check return of scanf as well as number
{
printf("Number of triangles (must be greater than 2) = ");
}
循环将迭代直到scanf
成功并且num_of_triangles
小于3
为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.