在C中区分字母和整数 [英] Distinguish between a letter and integer in C

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

问题描述

请注意,我并不是要像ctype.h中的isalpha()这样的功能来区分数字和字母(或其他字符)。

Please note that I'm NOT trying to distinguish between a single digit and a letter (or other character) as done by functions like isalpha() in ctype.h

我正在尝试区分整数和字母。

I'm trying to distinguish between an integer and an alphabet.

问题是,字母在C中也被视为整数,我想不到

The problem is that an alphabet is also treated as an integer in C and I can't think of a way out.

例如:如果输入为
,则字母a,
与 a相同,即整数97

eg: if input is the letter a, it is the same as 'a' which is the integer 97.

我需要确定输入的是'a'还是97。

And I need to find if 'a' or 97 was the input.

int a;
scanf("%d", &a);
if( (a>='A' && a<='Z') || (a>='a' && a<='z') )
{
   printf("\nAlphabet");
}


推荐答案

检查 scanf()

int val;
int chk = sscanf("a", "%d", &val);
if (chk == 1) /* all ok */;
if (chk == 0) /* no assignments */;
if (chk == EOF) /* error */;

int val;
int chk = sscanf("97", "%d", &val);
if (chk == 1) /* all ok */;
if (chk == 0) /* no assignments */;
if (chk == EOF) /* error */;

int val1, val2, val3;
int chk = sscanf("97 b 99", "%d%d%d", &val1, &val2, &val3);
if (chk == 3) /* all ok */;
if (chk == 2) /* only val1 and val2 were assigned a value */;
if (chk == 1) /* only val1 was assigned a value */;
if (chk == 0) /* no assignments */;
if (chk == EOF) /* error */;

这篇关于在C中区分字母和整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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