0

I learn C++ by a book, and always when I have a task to do, I'll add some of my features. Now I wanted to add "check for dummy people", and if they write fractional number, not integer, the console will be closed. I wanted to do like that:

cin >> timing;
if (timing == double) { 
    ...

But the Visual Studio compiler says "type name is not allowed".

Please, tell me how to do this check

Alex U
  • 1
  • 3
  • 6
    variables have static types. Therefore the shown code doesn't make sense and would never be necessary – UnholySheep Sep 16 '22 at 13:56
  • 3
    What you probably want to do instead is read the input into a `std::string` then use one of the parsing functions (such as `std::stod` : https://en.cppreference.com/w/cpp/string/basic_string/stof) to check if you can convert the text into a `double` – UnholySheep Sep 16 '22 at 13:57
  • 3
    Whatever book you're using it doesn't seem to to a very good job. [Here's a list of books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) that are commonly recommended. If possible please invest in one or two of the beginners books from the list. – Some programmer dude Sep 16 '22 at 14:00
  • How to do string input I know. But what parsing functions do you mean? And I don't know any convert functions, 'cause I'm newbie( I hope you will answer in details. Anyway, thank you :) – Alex U Sep 16 '22 at 14:02
  • You probably would have to make `timing` a std::string then write a function to check if the string looks like a double. This is not really a newbie type project. Wait till you learn more c++ before attempting. – drescherjm Sep 16 '22 at 14:03
  • I've already understood that, thanks) But what functions can we use for check? – Alex U Sep 16 '22 at 14:04
  • Thank you, but your comment makes no sense. I asked about my problem and asked how to solve it, not about "I read this book - is it good or not?" – Alex U Sep 16 '22 at 14:05

1 Answers1

1

The type of your timing variable is static, as are all types in C++. I'm going to assume it's an std::string. It will never be a double or an int. What you can do with it, is translate the information stored in it into another object of a different type.

For example, with std::stod you can try and convert the string into a double. This will return a double for all inputs, e.g. "3.1", "0", "horse", or "". For the last two, however conversion will fail, and std::stod will throw. However, the return value is always a double.

Now, you can check if the double holds an integral value. For instance you can convert the value to long and back and check if you get the same value. There are more sophisticated ways to check this, but it would be a good start.

bitmask
  • 32,434
  • 14
  • 99
  • 159