如何限制输入小数位数,直到用户可以输入值
How can i limit the input the number of decimals till which user can input value?
例如,接受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相当严格:它接受12
、012
、+12.3
、-12.34567
和0.12345
,但拒绝12.
、.5
、0.123450
和1.2e2
。您可能希望对其进行调整,以符合您的特定格式要求(无论它们是什么)。
您可以使用std::getline将一行读取为字符串,然后根据您的需要解析该字符串(并最终将其转换为double
,可能在其c_str()
上使用atof,或者最好是std::stof…)
你的例子不够精确:你应该接受453.210e-3
还是0.1234567e+3
等
你真的应该读书http://floating-point-gui.de/(我认为你的要求几乎是无用的)
相关文章:
- C++如何通过用户输入删除列表元素
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 用户定义函数中的指针和输入
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- 在C++中,我如何接受不同于同一行的用户输入
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 当用户键入分隔符时,停止getline()输入
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 当用户在qtablewidget中输入单元格时,如何获得信号?C++
- 显示基于用户输入的整数的字符
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 如果用户没有输入任何内容或输入错误,如何重新输入用户的输入?
- 为什么在代码块中执行时会跳过输入用户输入的行?
- 使用 for 循环在数组中输入用户