我正在尝试验证双数据类型的输入,我已成功部分因为如果用户输入的第一件事是字母,它将输出错误消息,但是如果用户在开头输入一个数字然后程序接受它,虽然它不应该。有想法该怎么解决这个吗?到目前为止,这是我的代码:
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();
}
答案 0 :(得分:0)
典型的习惯用法是读取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
}
语句中的值:
private void button_Click(object sender, RoutedEventArgs e)
{
TextBox tBox = new TextBox();
tBox.Width = 500;
tBox.Header = "Notes";
tBox.PlaceholderText = "Type your notes here";
}
这不处理数字后跟字母或无效符号的情况,例如“1.23A”或“1#76”。对于这些情况,您必须以字符串形式阅读文本并执行更详细的解析。
答案 1 :(得分:0)
另一种可能性,使用正则表达式检查输入的字符串是否为字符串!
// 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;
}
}
如果您需要负数,科学数字......,请调整正则表达式。