So I am currently learning C++ and decided to make a program that tests my skills I have learned so far. Now in my code I want to check if the value that the user enters is a double, if it is not a double I will put a if loop and ask them to reenter it. The problem I have is how do I go about checking what type of variable the user enters, ex- if a user enters a char or string, I can output an error message. Here is my code:
//cubes a user entered number #include <iostream> using namespace std; double cube(double n); //function prototype int main() { cout << 'Enter the number you want to cube: '; //ask user to input number double user; cin >> user; //user entering the number cout << 'The cube of ' << user << ' is ' << cube(user) << '.' << endl; //displaying the cubed number return 0; } double cube (double n) //function that cubes the number { return n*n*n; // cubing the number and returning it }
Edit: I would have to say I just started and don’t have the slightest of clue about your code, but I will check out your link. By the way, I haven’t learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.
There is no suitable way to check if a string really contains a double within the standard library. You probably want to use Boost. The following solution is inspired by recipe 3.3 in C++ Cookbook: