验证c中数字的输入
如何验证用户输入的数字,如果用户输入的是数字(字符串、字符等)而不是数字,则应在中显示错误。c编程语言当在输入中找不到任何数字时,该程序将查找并给出错误,并指定字符作为输入的索引 如果要声明数字,可以使用一系列if-else条件 这里我基本上是区分数字和字符验证c中数字的输入,c,C,如何验证用户输入的数字,如果用户输入的是数字(字符串、字符等)而不是数字,则应在中显示错误。c编程语言当在输入中找不到任何数字时,该程序将查找并给出错误,并指定字符作为输入的索引 如果要声明数字,可以使用一系列if-else条件 这里我基本上是区分数字和字符 #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int i; char a[100];
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i;
char a[100];
printf("enter the input value");
replay:
scanf("%s",&a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]=='1'||a[i]=='2'||a[i]=='3'||a[i]=='4'||a[i]=='5'||a[i]=='6'||a[i]=='7'||a[i]=='8'||a[i]=='9'||a[i]=='0')
{
printf("It Contains only numbers");
}
else
{
printf("\n error occured in %c position %d:\nEnter a valid number:",a[i],i);
goto replay;
}
}
}
#包括
#包括
#包括
int main()
{
int i;
chara[100];
printf(“输入值”);
重播:
scanf(“%s”、&a);
对于(i=0;a[i]!='\0';i++)
{
如果(a[i]='1'| a[i]='2'| a[i]='3'| a[i]='4'| a[i]='5'| a[i]='6'| a[i]='7'| a[i]='8'| a[i]='9'| a[i]='0')
{
printf(“它只包含数字”);
}
其他的
{
printf(“\n在%c位置%d发生错误:\n请输入有效数字:”,a[i],i);
转到重播;
}
}
}
@Blaze通常不建议使用scanf
。太多的事情会出错。例如,如果此代码在循环中运行<代码>字符*错误;双值=STROD(输入和错误);/*选中errno、*err*/或use-not-usescanf
。使用fgets
并自己使用sscanf
或strtod
、strtol
等扫描字符串。scanf可能导致误报,例如使用if(sscanf(“42foo”)、“%d”、&n)==1)/*“42foo”接受为数字*
实际上只有在确定输入格式与scanf格式字符串匹配时,才应使用scanf
函数系列。您无法确定用户输入的任何内容。代码第13行中的if语句应被视为包含在代码中