Sunday, July 12, 2009

In the C programming language, how do I test whether a variable is an integer?

I have a variable x. I want to test whether x is an integer (and not, for instance, a char variable). How do I do this?

In the C programming language, how do I test whether a variable is an integer?
C doesn't have introspection in this way, but surely you know what type x is declared as?


What problem are you actually trying to solve?





You can do some limited checking with something like


if (sizeof (x)) != sizeof (int)){.....





But that only checks that the sizes in memory match which is not that useful as in many common implementations, sizeof (float) == sizeof (int).





C++ has typeof, but that is not present in standard C, so your best bet is to just look at the declaration of x.





Sometimes there are compiler specific tricks, for example gcc has an extension that allows you to check that the arguments to a varargs function would be the correct type if that function was printf... It only generates a compile time warning, but it might allow you to come up with something.





Just a note that try/catch and typeof are C++, not C!





Regards, Dan.
Reply:pwnd.
Reply:very simple.





if int(num_entered) = num_entered then
Reply:bool IsInt(double x){return (double(long(x)) - x) == 0;};





this will only accept a double, so wrap your call to the IsInt method in a try catch block





It'll reach the catch block if it's not a double -
Reply:You must have declared the variable at some point.


Just look there.


C is not C++ no type of and certainly no try catch
Reply:Use the 'typeof' operator. For example, where b is the variable you need to check,





if (typeof(b) == typeof(int))


// do whatever, b is an int
Reply:Your math library should have isint routine.
Reply:Since you want to do some input error handling, we should accept input to a string and then check to ensure the string is valid.





#include %26lt;ctype.h%26gt;


#include %26lt;stdio.h%26gt;








void main()


{





const int MAX_LEN = 80;


char input_string[MAX_LEN + 1];


int valid_input = 1;





fgets(input_string, (MAX_LEN + 1), stdin);





// Note: If fgets() returns NULL then either an error occurred


// or no input was entered.





for (int loop = 0; ((loop %26lt; MAX_LEN) %26amp;%26amp; (input_string[loop] != 0)); loop++)


{


if (isdigit(input_string[loop]) == 0)


{


valid_input = 0;


break;


}


}





// if (valid_input == 1), our string only had digits (the only


// acceptible characters in a non-negative integer).


// If (valid_input == 0), then it had something invalid


// included.





}

calling cards

No comments:

Post a Comment