c - 当用户输入不正确的值以避免程序崩溃时,C 中的数据验证

标签 c int user-input scanf validation

如何确保用户只输入一个整数值以使程序不会崩溃?

如果用户输入的不是整数,我想: printf("请重新检查您的输入);

printf("How many values do you want to enter? \t");
    int g;
    scanf("%d", &g);

最佳答案

我会说,检查 scanf 的返回值:

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.

关于c - 当用户输入不正确的值以避免程序崩溃时,C 中的数据验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25600370/

相关文章:

java - 使用模拟用户输入进行 JUnit 测试

arrays - 如果输入数组定义为 const,如何对其进行排序?

objective-c - c中的模拟器/生成的switch语句范围

c# - P/Invoke - 如何使用将地址返回到 double 组的 c 函数的结果来使访问加倍

c - Double 到 Float 数组转换和 Endian 交换

java - 使用 "char"与 "int"索引数组,有什么区别?

java - 我需要获取一个整数数组并将它们打印为金字塔

c++ - int 位运算

php - 你如何实现一个好的亵渎过滤器?

c - 使用相似代码时出现奇怪的编译器投诉