views:

53

answers:

1

Can we use __typeof__ for input validation in C program run on a Linux platform and how?

If we can't then, are there any ways other than regex to achieve the same?

+2  A: 

"typeof" is purely a compile-time directive. It cannot be used for "input validation."

Input validation rules can be complex. In C, they are made more complex by the fact that the tools that you have at your disposal in the standard C library are pretty awful. One example is atoi(), which will return 0 if the string that you pass in doesn't contain a number at the beginning (atoi("hello world") == 0), and "1337isanumber" will actually return 1337. To simply validate if something is a number, you could (assuming ASCII and not Unicode) use a loop and make sure each value up until the first null terminator (or the size of the memory you allocated for the string) that each digit is in fact numeric. A similar procedure could be done to check if something is alphanumeric, etc. As you mentioned, regexes can be used for a telephone number or some other relatively complex data format.

Your comment below references using "instanceof" in Java for input validation, but this isn't possible either. If you get user input from, say, the command line, or a query string parameter, or whatever, it really comes in as a string. If you're using a Scanner object to scan the standard input and use a method such as nextInt(), it's really converting a string (from the stream) into something, which can throw a runtime exception. You cannot use instanceof to determine a string's contents; a String is a String -- even if its contents are "42", it is not an instance of an Integer!

bowenl2
thanks for your time.Validating user input like say for e.g. user must input only numbers or user must only input string and no numbers, etc.. I had thought of using the typeof for checking the datatype of the entered input against the valid datatype. somewhat similar to instanceof operator in java.
Vishu
`strtol` can help with number sanity checking.
sixlettervariables