Jump to content

check if input is int float or char

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
raonavneet

raonavneet

    Newbie

  • Members
  • Pip
  • 1 posts
can someone give me simple code in c to check if the input enter by a user is an integer, float or a character

#2
bvaessen

bvaessen

    Newbie

  • Members
  • PipPip
  • 27 posts
Maybe there is something standard available in C for this. If not, you could try something like this:

int idx;

char str[STRINGLENGTH];

int numbersfound = 0;

int dotsfound = 0;

for (idx=0; (idx<STRINGLENGTH) && (str[idx]); idx++){

  numbersfound += ((str[idx] >= '0') && (str[idx] <= '9'));

  dotsfound += (str[idx] == '.');

}

if (numbersfound == STRINGLENGTH)

  printf("integer");

else if ((dotsfound == 1) && (numbersfound == STRINGLENGTH-1))

  printf("floating point");

else 

  printf("string");

--------------------------------------------------------------------
Ben Vaessen :: Home ::: Launch-IT :: Home

#3
Oigen

Oigen

    Programmer

  • Members
  • PipPipPipPip
  • 107 posts
Yea, that code seems to be pretty good. I compiled it and it worked as asked.

#4
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts

raonavneet said:

can someone give me simple code in c to check if the input enter by a user is an integer, float or a character
Maybe check the input string to first see whether it can be converted to an integer, then check to see whether it can be converted to a float, otherwise, assume neither?