双C++验证无法正常工作
问题描述:
我想验证双数据类型的输入,我已经部分成功了,因为如果用户输入的第一个内容是字母,它将输出错误消息,但是如果用户输入了编号在开始然后程序接受它,但它不应该。有想法该怎么解决这个吗?这里是我到目前为止的代码:双C++验证无法正常工作
void circleArea(double pi)
{
double radius = 0.0;
bool badInput;
do
{
cout << "*================*\n";
cout << " Area of a circle\n";
cout << "*================*\n\n";
cout << "Please enter the radius of your circle (numerics only):\n\n";
cin >> radius;
badInput = cin.fail();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while (badInput == true);
system("CLS");
cout << "The area of your Circle is:\n\n" << radius*radius*pi << "cm^2" << endl << endl;
exitSystem();
}
答
一个典型的成语是在if
语句读取值:
cout << "*================*\n";
cout << " Area of a circle\n";
cout << "*================*\n\n";
cout << "Please enter the radius of your circle (numerics only):\n\n";
if (!(cin >> radius))
{
cerr << "Invalid input, try again.\n";
}
else
{
// radius is valid
}
这不处理一个数字,后跟一个字母或无效符号的情况下,如“1.23A”或“1#76”。对于这些情况,您必须以字符串的形式读取文本并执行更详细的解析。
答
另一种可能性是,使用正则表达式来检查输入的字符串是否是一个字符串!
// Example program
#include <iostream>
#include <string>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
const boost::regex is_number_regex("^\\d+(()|(\\.\\d+)?)$");
//If I didn't make a mistake this regex matches positive decimal numbers and integers
int main()
{
double radius;
std::string inputstring;
std::cin >> inputstring;
boost::smatch m;
if(boost::regex_search(inputstring, m, is_number_regex))
{
radius = boost::lexical_cast<double>(inputstring);
std::cout <<"Found value for radius: "<< radius << std::endl;
}
else
{
std::cerr << "Error" << std::endl;
}
}
适应的正则表达式,如果你需要负数,科学的数字,...
_“但是,如果用户在一开始那么程序接受它,输入一个号码,虽然它不应该” _你能详细说明一下吗? “双”值自然会带数字? –
好吧,所以如果输入是像“5bffhds”(数字作为第一件事)那么该程序将不会认为它是失败的cin,而它是。如果输入类似“gfsd3fdj”,验证工作正常。 – PinkieBarto
将输入解析为字符串块,并使用'stod()'进行转换。 –