c - 在 C 编程中检查用户的验证
问题描述
这是我的代码片段。我很困惑为什么数字无法运行。如果我们输入字符/字母,它应该。该行是数字打印“请输入数字”,但不打印。我需要你对此的意见。
这是我的代码:
printf("\nenter the amount of food to be purchased : ");
scanf("%d", &b);
printf("\n");
if (b >= 0) {
for (a=1; a<=b; a++){
printf("the price of food of- %d \t : ",a);
scanf("%d", &c);
printf("\n");
if (isdigit(c)) {
printf("Please enter in numeric !!\n");
while ((getchar()) != '\n');
system("PAUSE");
goto cashier;
}
printf("the amount ordered \t : ");
scanf("%d", &d);
printf("\n");
if (isdigit(d)) {
printf("Please enter in numeric !!\n");
while ((getchar()) != '\n');
system("PAUSE");
goto cashier;
}
解决方案
scanf("%d", &c);
. 将一个整数读入 c。当您调用 时isdigit(c)
,您不是在检查输入的字符串是否为数字,而是在检查输入的数字是否对应于表示数字的 ascii 字符。这不是预期的行为。你想要的是这样的:
while (scanf("%d", &c) != 1) // Repeatedly get input until scanf reads 1 integer.
{
while (getchar()!='\n'); // Clear stdin.
puts("Please enter a number!");
}
// The resulting number is now stored in c.
这将尝试将数字(不是字符串)读入 c。如果用户没有输入 1 个数字,scanf()
则不会返回 1,循环将重试。确保 c 被声明为 anint
而不是 a char
,否则 128 以上的数字将溢出。
推荐阅读
- reactjs - 我是否必须将道具放入构造函数,因为它们位于 mapStateToProps 中?
- xaml - 内容对话框高度调整
- r - 如何增加ggplot2中图例的大小
- java - VelocityEngine 从字符串中删除转义字符
- algorithm - 什么时候值得使用更差的 Big-O 算法
- python - Keras:两个同时的层,其中一个对前一层的输出进行卷积
- python - 如何在 macos/osx 中捕获锁定/解锁事件时间
- r - 如何突出显示不在数据中的点?
- matlab - 尝试从 csv 文件加载混合数据并进行搜索
- java - 从 google+ 登录迁移到新的 google 登录