我正在尝试获取用户输入并允许他们只输入一个整数,这也是正数。
我想弄清楚这个任务
printf("Enter the first and second number in whole number: ");
scanf("%d,%d", &first, &second);
if (input != '\n') //notice this line I'm trying to check if is a character//
printf("Error! CHARACTER NOT ACCEPTED!!\n");
else if (First <= 0)
printf("Error! First must be a positive value!\n");
else if (Second <= 0)
printf("Error Second must be a positive value!\n");
上面的代码将检查两件事。一,如果用户输入了我想要的字符。第二,如果数字是正数。
我如何兑现这些支票?
最佳答案
读取整行(使用 getline
),然后将其转换为数字,可能使用 strtol
(并测试结束指针)。
或者对scanf
使用%n
格式并测试scanf
返回的(成功转换的)数量
关于c - 如何限制用户只能输入整数并拒绝 scanf 中的任何其他字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8194521/