【发布时间】:2021-07-01 03:03:17
【问题描述】:
我编写了一个程序,通过用户输入计算圆柱和矩形区域。但我想改进我的代码。当用户输入字符而不是数字时,它应该输出错误消息。所以我写了一些额外的代码,但它不能正常工作。
#include <iostream>
#include <ctype.h>
using namespace std;
class area_cl
{
public:
double height, width;
};
class rectangle : public area_cl
{
public:
double area(double h, double w)
{
return h * w;
}
};
class cylinder : public area_cl
{
private:
double pi = 3.14;
public:
double area(double h, double w)
{
return 2 * pi * (w / 2) * ((w / 2) + h);
}
};
int main()
{
area_cl dimension;
rectangle obj1;
cylinder obj2;
bool flag = true;
while (flag)
{
cout << "What is the dimensions? (Height and Width)" << endl;
cin >> dimension.height >> dimension.width;
if (isdigit(dimension.height) && isdigit(dimension.width))
{
flag = false;
}
else
{
cout << "You are not entered number,please try again." << endl;
}
}
cout << "Rectangle's area is : " << obj1.area(dimension.height, dimension.width) << endl;
cout << "Cylinder's area is : " << obj2.area(dimension.height, dimension.width) << endl;
return 0;
}
-
我曾想过使用
isdigit(),但我的输入变量必须是双精度类型,而且我的代码可能会因此而崩溃。 C++中有没有什么方法,比如C#中的解析? -
我还考虑过使用 ASCII 码控制输入。例如
if ( char variable >= 48 && char variable <= 57),但我无法让它工作。
我更愿意用第一个选项来解决这个问题,但我完全愿意接受其他解决方案。
谢谢。
【问题讨论】:
-
这可能会有所帮助:stackoverflow.com/questions/24504582/… 不,
isdigit()不检查double类型,只是数字,不多不少。
标签: c++ validation input io cin