For the following code, a number is inputed and the cube of that number is displayed. When anything other than a number is inputed, for example a letter, the message “Please Enter a number.” should be displayed once. The problem is that the same message is being displayed endlessly and I have no idea why this is.
If I take out “return main()” from the main() function, then I don’t get this endless display of the same message when a number is not inputed. However, I want the program to repeat so that users can enter as much numbers as they want. Does anyone know a solution to this?
//cubes a user entered number
#include <iostream>
using namespace std;
double cube(double n); //function prototype
double user;
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
if ( !(cin >> user) ) {
cout << "Please Enter a number." << endl;
} else {
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
}
return main();
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}