如何在vc ++中验证数字字符串 [英] How to validate a numeric string in vc++
问题描述
大家好,
我是vc环境中的新手。是否有人建议我如何验证数字字符串?
我的要求如下:
a)数字字符串有负数。
b)范围来自 - 1000到1000.
目前我做以下事情:
a)删除前导零。
b)删除特殊符号和字母。
c)仅限制四个字符的字符串。
用户输入任何类型的组合,如:
a)-1-0
b)1-00
c) - 00
等等。
我不明白如何限制上面的那个。
请有人建议我这件事。
Hi everybody,
I am new in vc environment. Is some one suggest me how I validate the numeric string?
My requirements are as follows:
a)numeric string have negative numbers.
b)range is from -1000 to 1000.
Currently I do the following things:
a)remove leading zeros.
b)remove special symbols and alphabets.
c)restrict the string only for four characters.
User enters combinations of any type like :
a)-1-0
b)1-00
c)--00
and so on.
I am not understanding how to restrict the above one.
Please anyone suggest me regarding to this things.
推荐答案
有像atoi,atof,atol这样的内置函数。
通过使用此功能,您不需要关心restictions:给定的字符串将被转换或您回零!
看看例如atoi:
There are built-in functions like atoi, atof, atol and so long.
By using this function you don''t need to care of restictions: the given string will be converted or you get zero back!
Take a look at e.g. atoi:
function
atoi
<cstdlib>
int atoi (const char * str);
Convert string to integer
Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.
例如:
For example:
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atoi */
int main ()
{
int i;
char buffer[256];
printf ("Enter a number: ");
fgets (buffer, 256, stdin);
i = atoi (buffer);
printf ("The value entered is %d. Its double is %d.\n",i,i*2);
return 0;
}
这些是标准模板解决方案:
These are standard template solutions:
#include <string>
#include <sstream>
#include <stdexcept>
// Checks if a std::string can be converted to a type T.
template <typename T> bool Is(const std::string& s)
{
T value;
std::istringstream is(s);
is >> value;
if(!(is && (is >> std::ws).eof()))
return false;
return true;
}
// Converts a std::string into a type T.
// (A std::invalid_argument exception is thrown if the conversion is not possible).
template <typename t=""> const T To(const std::string& s)
{
T value;
std::istringstream is(s);
is >> value;
if(!(is && (is >> std::ws).eof()))
throw std::invalid_argument("Function: To<t>. Unallowed conversion.");
return value;
}
</t></typename>
没有限制,所以你应该转换后应用限制。
我担心这不适用于你所指出的奇怪输入。 (与-00一起使用,但不与其他人一起使用)。
我希望这会有所帮助。
祝你好运!
No restrictions are done, so you should apply restrictions after conversion.
I am afraid this does not work with strange inputs as you have pointed out. (Works with "-00" but not with the others).
I hope this sheds some light.
Best regards!
这篇关于如何在vc ++中验证数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!