简体   繁体   English

C中字母和整数的区别

[英]Distinguish between a letter and integer in C

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请注意,我不是要像 ctype.h 中的 isalpha() 等函数那样区分单个数字和字母(或其他字符)

I'm trying to distinguish between an integer and an alphabet.我试图区分整数和字母表。

The problem is that an alphabet is also treated as an integer in C and I can't think of a way out.问题是字母表在 C 中也被视为整数,我想不出出路。

eg: if input is the letter a, it is the same as 'a' which is the integer 97.例如:如果输入是字母a,则它与'a'相同,即整数97。

And I need to find if 'a' or 97 was the input.我需要找出输入的是 'a' 还是 97。

I tried to do this and realised it simply couldn't work.我试图这样做并意识到它根本无法工作。

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

Check the return value of scanf()检查scanf()的返回值

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

or或者

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

or或者

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 */;

You don't have to distinguish it after scanf because it had already distinguished it:scanf之后你不必再区分它,因为它已经区分了它:

  • %d only input integer, so you just can enter integer => if you write 9, you will store 9 inside variable. %d只输入整数,所以你可以输入整数 => 如果你写 9,你将把 9 存储在变量中。 You can't read character with this ( demo ).不能用这个( demo )读取字符。 Also, if you input 97, it will store 97 inside variable, which also correspond to code associated to a此外,如果您输入 97,它将在变量中存储 97,该变量也对应于与关联的代码
  • %c only input character => if you write 9, you will store associated code of character 9, ie 57 %c只输入字符 => 如果你写 9,你会存储字符 9 的关联代码,57

You can check return of scanf to know if it succeed read something or not.您可以检查scanf返回以了解它是否成功读取某些内容。

So, if user can input both character and letter, a possible solution is to acquire only character with %c and to recreate integer during typing of user:因此,如果用户可以输入字符和字母,则可能的解决方案是仅获取带有%c字符并在用户键入期间重新创建整数:

int i = 0;
int dec = 1;
char c;
scanf("%c", &c);
if (c >= '0' && c <= '9')
{
    i += c*dec;
    dec *= 10;
}
else
{
    // manage letter
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM