how to exclude in C programming

chipy

Golden Member
Feb 17, 2003
1,469
2
81
thanks to all who replied to my previous post!

now i am trying to do this:

if (variable != int)
;

else
printf("You did not input an integer! Try again.\n");

however, i know i can't use "int" like i demonstrated in the code above. if i want to make sure that what the end user entered was indeed an int and not a decimal number, letter, symbol, or string of characters, how would i go about coding that?

thanks,
chipy
 

trek

Senior member
Dec 13, 2000
982
0
71
Originally posted by: chipy
thanks to all who replied to my previous post!

now i am trying to do this:

if (variable != int)
;

else
printf("You did not input an integer! Try again.\n");

however, i know i can't use "int" like i demonstrated in the code above. if i want to make sure that what the end user entered was indeed an int and not a decimal number, letter, symbol, or string of characters, how would i go about coding that?

thanks,
chipy

this is from memory so it may not be correct.

using this method i think it will read 12.1231 as 12 still, so it may not be exactly what you need.
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
trek's code should work. If you want to actually see if they entered an int, I'd suggest something more along the lines of:

char buf[256];
int theNum, i;

fgets(stdin, buf, 256);

for(i=0; i<strlen(buf); i++)
...if(((buf[ i ]-'0') < 0) || ((buf[ i ]-'0') > 9)) /* the spaces around "i" are to avoid fusetalk junk */
...{
......printf("not an int\n");
......break;
...}
 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,589
5
0
Originally posted by: CTho9305
trek's code should work. If you want to actually see if they entered an int, I'd suggest something more along the lines of:

char buf[256];
int theNum, i;

fgets(stdin, buf, 256);

for(i=0; i<strlen(buf); i++)
...if(((buf[ i ]-'0') < 0) || ((buf[ i ]-'0') > 9)) /* the spaces around "i" are to avoid fusetalk junk */
...{
......printf("not an int\n");
......break;
...}

Another option would be
fgets(stdin,buf,256);
int i = strlen(buf);
while (i--)
if ((buf > 0x30) || (buf < 0x39))
{
// error handling
break;
}

This method will use less execution cycles due to handling of the while loop and testing.
I used the hex equivalent of the value 0 and 9 instead of the character equivalent - the compiler will treat each the same.