我目前正在学习C++并决定制作一个测试我已经学到的技能的程序。现在在我的代码中,我想检查用户输入的值是否为double类型,如果不是double类型,我将放置一个if循环并要求他们重新输入。我遇到的问题是如何检查用户输入的变量类型,例如,如果用户输入char或string,我可以输出错误消息。以下是我的代码:
//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
}
编辑:我必须说我刚开始,对你的代码一无所知,但我会查看你的链接。顺便说一下,我还没有学习如何使用模板,我正在学习处理数据,只有C++ Primer Plus第5版的第3章。