简体   繁体   中英

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

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.

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

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

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()

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:

  • %d only input integer, so you just can enter integer => if you write 9, you will store 9 inside variable. You can't read character with this ( demo ). Also, if you input 97, it will store 97 inside variable, which also correspond to code associated to a
  • %c only input character => if you write 9, you will store associated code of character 9, ie 57

You can check return of scanf to know if it succeed read something or not.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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