如何验证数字 [英] How to validate numbers
问题描述
基本上,我想知道如何声明程序在有人输入字符时不会搞砸
我以为可能是
while(height!=``float'')loop等
但是这种方法不起作用,而且确实会搞砸.请帮忙!
Right basically I want to know how to declare the program to not screw up when someone enters a character
I thought it might be something like
while( height != ''float'')loop etc
but that dose not work and it does screw up. Please help!
推荐答案
您可以定义定义数字的规则,只需为此创建代码
您将需要类似以下规则的代码:
1.可以以可选的减号(``-'')
开头 2. 1个或多个数字(``0''.``9'')
3.可选的单个点(''.''),再次为否2.
第二种选择是考虑使用正则表达式(此示例仅接受数字0..9).
You could define the rules that define a number and simply create code for that
You would need code to rules like:
1. can start with an optional minus (''-'')
2. 1 or more digits (''0''..''9'')
3. optional a single dot (''.'') and again no 2.
A second option is to consider using a regex expression (this example only accepts digits 0..9).
string Temp = "Hax00r L33t";
string Output = Regex.Replace(Temp, "[^0-9]", "");
祝你好运!
Good luck!
键盘输入验证始终是一个挑战.此函数处理一些常见情况:
Hi,
Keyboard input validation is always a challenge. This function handles some usual cases:
#include <sstream>
template <class Num>
bool Validate(const std::string& input, Num& num)
{
Num tmp;
std::istringstream iss(input);
iss >> std::skipws >> tmp >> std::skipws;
return iss.eof() && !iss.fail() ? num = tmp, true : false;
}
请检查:
Check with:
#include <iostream>
int main()
{
std::string input;
for (;;)
{
std::getline(std::cin, input); // get all input
int i = 0;
bool bint = Validate(input, i);
float f = 0;
bool bfloat = Validate(input, f);
}
return 0;
}
"123","123""-123"被验证为int和float.
"12 3","12 3"-123"作为int和float无效.
"123.",".123""-12.3""-.123e4"被无效为int并被验证为float.
欢呼声,
AR
"123", " 123 " "-123" are validated as int and float.
"12 3", " 12 3 " "- 123" are invalidated as int and float.
"123.", " .123 " "-12.3" " -.123e4 " are invalidated as int and validated as float.
cheers,
AR
这篇关于如何验证数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!