• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

how to exclude in C programming

chipy

Golden Member
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
 
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.
 
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;
...}
 
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.

 
Back
Top