如何限制输入小数位数,直到用户可以输入值

How can i limit the input the number of decimals till which user can input value?

本文关键字:输入 用户 何限制 小数      更新时间:2023-10-16

例如,接受4.55324作为用户输入,如果输入6.22356则拒绝,即接受至小数点后5位。

最简单的方法是将输入读取为字符串,检查它是否与所需的格式匹配,然后将其转换为数字。例如,使用C++11正则表达式功能进行验证:

double number;
std::string input;
std::cin >> input;
std::regex pattern ("^[-+]?[0-9]+(.[0-9]{1,5})?$");
if (std::regex_match(input, pattern)) {
    number = std::stod(input);
}
else {
    // handle invalid input here
}

请注意,上面的regex相当严格:它接受12012+12.3-12.345670.12345,但拒绝12..50.1234501.2e2。您可能希望对其进行调整,以符合您的特定格式要求(无论它们是什么)。

您可以使用std::getline将一行读取为字符串,然后根据您的需要解析该字符串(并最终将其转换为double,可能在其c_str()上使用atof,或者最好是std::stof…)

你的例子不够精确:你应该接受453.210e-3还是0.1234567e+3

你真的应该读书http://floating-point-gui.de/(我认为你的要求几乎是无用的)