检查输入整数输入C [英] Check if input is integer type in C

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

问题描述

美中不足的是,我不能使用的atoi或任何其他功能一样,(我是pretty确保我们应该依靠数学运算)。

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)

但这些都不奏效。

but none of these worked.

任何想法?

推荐答案

NUM 将始终包含一个整数,因为它是一个 INT 。该的真正的问题与您code是你不检查 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).

由于您的评论,你只希望让用户输入一个整数,然后按Enter键。不幸的是,这不能简单地通过 scanf函数(%d个\\ N)实现,但这里有一个窍门做到这一点:

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\n"), but here's a trick to do it:

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

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

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