输入123、+123、-123、(空格)+123,返回是有效整数;输入123.4、.5、-.5、+.5、(空格)0.2,返回的是有效double型;输入123.4.5.6、f123、-(空格)0.2、-0.(空格)2、0.+2等返回的是无效数据。我的代码如下,思路不成熟,所以效果没达到,麻烦高手把把关。int main(int argc, char **argv){char buffer[LINELEN];char *fgets_rtn = NULL;int i;int point_flag = 0;for ( i = 0; buffer[i] != 0 ;){fgets_rtn = fgets(buffer, LINELEN, stdin);if ( NULL == fgets_rtn ){return 0;}if ( '\n' == buffer[strlen(buffer) -1]){buffer[strlen(buffer) -1] = '\0';}if (i==0&&(isdigit(buffer[i]) == 1||isspace(buffer[i]) == 1||buffer[i]=='+'||buffer[i]=='-')){i++;}if (buffer[i]=='.'){i++;point_flag++;}if (isdigit(buffer[i]) == 1){ i++;if (point_flag == 1){printf( "%s is a valid double\n", buffer);}if (point_flag > 1){printf( "%s is not a valid number...\n", buffer);} if (point_flag == 0){printf("%s is a valid integer\n",buffer);}}else{printf("%s is not a valid number\n",buffer);}}return 0;}
2 回答
呼如林
TA贡献1798条经验 获得超3个赞
抽出来判断部分。
int isValidInt( char * str) { while ( isspace (str) || *str == '\0' ) ++str; if (*str == '\0' ) return 0; if (*str == '+' || *str == '-' ) ++str; while (*str != '\0' ) { if (! isdigit (*str)) return 0; ++str; } return 1; } |
大概这样。
- 2 回答
- 0 关注
- 70 浏览
添加回答
举报
0/150
提交
取消