0

I'm learning C. I wonder whether there is an instruction or command to recognize the type of the variable.

To be more practical: I have a program which works with integers, I want to show an error message if the user inserts a real number when running the program.

Hope you can help!

  • 4
    Can you post some code that you have written to try to do this? – rabbit Jul 31 '15 at 19:59
  • 2
    Sounds like you want to validate *user input* rather than prevent programmers from passing double parameters to your int functions. Validating input has little to do with determining the type of a variable. – John Coleman Jul 31 '15 at 20:12
  • @tidus: Check this out http://stackoverflow.com/questions/15228388/input-validation-using-scanf – Jeremiah Dicharry Jul 31 '15 at 20:31
  • 1
    At a low level, any input from the user's keyboard is a string, and it has to be converted first before it can be stored in an `int`. So what you mean to ask is, given a string, how do you determine whether it contains an integer or not. For example, see [Determine if a C string is a valid int in C](http://stackoverflow.com/questions/9753346/determine-if-a-c-string-is-a-valid-int-in-c). – Lithis Jul 31 '15 at 20:32
  • 1
    If all you want to do is make sure that the user doesn't enter something like "2.3" but you don't care if they enter "2.0", and you are just using scanf (likely if you are a newbie) what you can do is read the input into a *double* variable, assign the result to an *int* and then compare the difference between the two variables. – John Coleman Jul 31 '15 at 20:42
  • my fault if I've not been enough clear. My doubt was something like @JohnColeman said. I'll try his solution. thanks! –  Aug 01 '15 at 08:42
  • Alternatively function like strtol can convert a string to a long int and report convertion errors: http://stackoverflow.com/questions/7021725/converting-string-to-integer-c – OAnt Aug 01 '15 at 10:20

1 Answers1

2

This is not part of the C standard, but GCC has the typeof keyword.

You have to be using the GCC compiler for it though.

  • this is probably not what the OP means, as `typeof` works at compile time, but the user is entering input at runtime. – wimh Jul 31 '15 at 20:16
  • @Wimmel You are probably correct that it doesn't answer OP's (not very well researched) question -- but it does provide a potentially useful partial answer to the question implicit in the title of this question. It doesn't really address OP's concerns -- but it might address the concerns of someone searching SO in the future for determining the type of variables in C. – John Coleman Jul 31 '15 at 20:21
  • @JohnColeman ok, I'll upvote ;) – wimh Jul 31 '15 at 20:38