我目前正在开发一个用C语言编写的程序,该程序使用scanf从用户获取输入。我希望程序在用户输入数字以外的内容时终止。
目前,我使用的代码如下:
while(scanf("%c", &value) == 1) {
if(isdigit(value)) {
scanf("%c", &value);
push(&head, value);
count++;
}
else {
break;
}
}我使用isdigit来检查输入是否是0-9之间的数字,但是如果用户输入的内容是..."52“。
有没有isdigit的替代品可以处理这个问题?如有任何建议,我们将不胜感激!
发布于 2020-03-16 15:52:28
您不能将"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;
}https://stackoverflow.com/questions/60699875
复制相似问题