判断字符串是否为一个有效的数
判断字符串是否为一个有效的数int is_dec_str(char * str, int * p_or_n, int * i_qty, int * d_qty, int * dot_pos);
/* is_dec_str() return 1 if Yes, otherwise 0
* Check str if a valid decimal number or not. Return 1 if Yes, or 0 if No.
* str: the string to be checked.
* p_or_n: indicate the number is positive (1) or negative (-1) (after check).
* i_qty: integeral part char qty (length)
* d_qty: decimal part char qty (length)
* dot_pos: return position of '.', (or '\0' if no '.'), of the str
* eg: if p_or_n = -1, i_qty = 5, d_qty = 2, dot_pos = 6 str may look like -nnnnn.nn
*/
int is_dec_str(char * str, int * p_or_n, int * i_qty, int * d_qty, int * dot_pos)
{
int ret_val = 1; //return value, 1 = Yes, 0 = No.
int dot_qty = 0; //'.' qty found in the str
int i = 0; //i is an index of str.
switch (str)
{
case '-': *p_or_n = -1; i++; break; //negative number and bypass the '-'
case '+': i++; //bypass the '+'
default: *p_or_n = 1; //positive number
}
*i_qty = 0;
*d_qty = 0;
*dot_pos = -1; //initialized as a not possible value.
while (str != '\0' && ret_val)
{
switch (str)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': dot_qty ? ++(*d_qty) : ++(*i_qty);
break;
case '.': if (++dot_qty > 1)
ret_val = 0; //Error: too many '.'
*dot_pos = i;
break;
default: ret_val = 0; //Error: unexpected char found
}
i++;
}
if (*i_qty == 0 && *d_qty == 0)
ret_val = 0; //Error: no valid number found
if (*dot_pos == -1) //there is no '.' in the str, str is an integer
*dot_pos = i; //dot_pos set at '\0'(str end) for "no dot" integer
if (ret_val != 1)
{
*p_or_n = 0;
*i_qty = 0;
*d_qty = 0;
*dot_pos = 0;
}
return ret_val;
}
#include <stdio.h>
int main() {
char *test_str = "-123.45";
int sign, int_qty, dec_qty, dot_pos;
if (is_dec_str(test_str, &sign, &int_qty, &dec_qty, &dot_pos)) {
printf("有效的十进制数字:\n");
printf("符号: %d\n", sign);
printf("整数部分字符数量: %d\n", int_qty);
printf("小数部分字符数量: %d\n", dec_qty);
printf("小数点位置: %d\n", dot_pos);
} else {
printf("无效的十进制数字。\n");
}
return 0;
} 正则表达式 简化一下,如果计算机都处理不了的数就不算有效的,convert.tofloat()如果报错就不是数字不行么 n_g 发表于 2024-9-14 19:42
简化一下,如果计算机都处理不了的数就不算有效的,convert.tofloat()如果报错就不是数字不行么
{:1_921:}老哥这是C++范畴,可是我想放到C里去用。 CoinsBtc 发表于 2024-9-14 17:12
正则表达式
只用过linux的正则表达式,太难用,根本记不住。
C用正则表达式需要额外的库的吧,没用过。 王者霸主 发表于 2024-9-14 17:08
#include
int main() {
嗯嗯,可以试试 -1111111111111111111111111111111111111111111111111111111111111111.222222222222222222222222222222222222222222222222222222222222222222222222222222222
使用stringstream非常方便,只需要比较转换前后两个字符串的长度就可以判断原字符串中是否只含有数字{:301_978:}
#include <iostream>
#include <ostream>
#include <sstream>
#include <string>
int main() {
double num;
std::string str = "123.56abc!@#";
std::stringstream ss;
ss << str;
ss >> num;
std::string str2;
ss.clear();
ss.str("");
ss << num;
ss >> str2;
std::cout << str.length() << std::endl;
std::cout << str2.length() << std::endl;
return 0;
}
条条大路通罗马,方法有很多种。 哈利菜菜 发表于 2024-9-14 20:27
条条大路通罗马,方法有很多种。
这是只用了C内置功能
页:
[1]
2