c - 替代 isdigit 来读取大于 9 的数字?
问题描述
我目前正在使用 C 语言编写一个程序,该程序使用scanf
. 我希望程序终止是用户输入了数字以外的内容。
目前,我正在使用以下代码:
while(scanf("%c", &value) == 1) {
if(isdigit(value)) {
scanf("%c", &value);
push(&head, value);
count++;
}
else {
break;
}
}
我isdigit
用来检查输入是否是 0-9 之间的数字,但如果用户要输入类似“52”的内容,这会带来问题。
有没有替代方案isdigit
可以处理这个问题?任何意见,将不胜感激!
解决方案
您不能将“52”存储到 char 而不是试试这个,
#include <stdio.h>
#include <ctype.h>
int myisdigit(char *str)
{
while(*str)
{
if(!isdigit(*str))
return 0;
str++;
}
return 1;
}
int main()
{
char str[10];
scanf("%s",str);
if(myisdigit(str))
printf("digit");
else
printf("non digit");
return 0;
}
您也可以将 myisdigit 更改为
int myisdigit(char *str)
{
while(*str)
{
if( ! ( ( ( *str ) >= '0' ) && ( (*str) <='9' ) ) )
return 0;
str++;
}
return 1;
}
推荐阅读
- sql-server - SQL-Server - 使用内连接更新,输出也使用内连接
- python - 在 Pandas 中调用 resample() 时出现 TypeError
- java - 模拟选举的蒙特卡罗模拟
- javascript - AngularJs - 如何在同一个 JSP 中调用父控制器
- hadoop - 如何通过从另一个配置单元表中的 5 个不同列中获取唯一值来在配置单元表中插入一列
- php - CRUD - 在 Laravel 上删除
- f# - 针对 List 变量的模式匹配
- c++ - 参数不能被初始化
- javascript - 在 safari 和 safari mobile 中加载下一个网页时显示微调器
- sql - 按资源消耗划分的 row_number()