检查输入是否为 C 中的整数类型 [英] Check if input is integer type in C

查看:22
本文介绍了检查输入是否为 C 中的整数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是我不能使用 atoi 或任何其他类似的函数(我很确定我们应该依赖数学运算).

The catch is that I cannot use atoi or any other function like that (I'm pretty sure we're supposed to rely on mathematical operations).

 int num; 
 scanf("%d",&num);
 if(/* num is not integer */) {
  printf("enter integer");
  return;
 }

我试过了:

(num*2)/2 == num
num%1==0
if(scanf("%d",&num)!=1)

但这些都没有用.

有什么想法吗?

推荐答案

num 将始终包含一个整数,因为它是一个 int.您的代码的真正问题是您没有检查 scanf 返回值.scanf 返回成功读取的项目数,所以在这种情况下,它必须为有效值返回 1.如果不是,则输入了无效的整数值,并且 num 变量可能没有更改(即仍然具有任意值,因为您没有对其进行初始化).

num will always contain an integer because it's an int. The real problem with your code is that you don't check the scanf return value. scanf returns the number of successfully read items, so in this case it must return 1 for valid values. If not, an invalid integer value was entered and the num variable did probably not get changed (i.e. still has an arbitrary value because you didn't initialize it).

根据您的评论,您只想允许用户输入一个整数,然后按回车键.不幸的是,这不能简单地通过 scanf("%d ") 实现,但这里有一个技巧:

As of your comment, you only want to allow the user to enter an integer followed by the enter key. Unfortunately, this can't be simply achieved by scanf("%d "), but here's a trick to do it:

int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '
')
    printf("failure
");
else
    printf("valid integer followed by enter key
");

这篇关于检查输入是否为 C 中的整数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆