我如何只接受C中的数字并阻止用户输入字母和特殊字符?

时间:2014-09-29 18:34:34

标签: c validation input

我只需要弄清楚如何给出错误,即用户输入的不是数字。我已经设置了无法传递或被删除的代码值。

我只需要接受数字:如果输入了一个字母或任何类型的特殊字符,我希望程序只是取消它自己。我怎么能这样做?

#include <stdio.h>
#include <math.h>

int main(void) {
    float base, height;
    float area;

    printf("Please enter the value of base of the triangle: \n");
    scanf ("%f", &base);
    if(base<.5)
        printf("Invalid Input\n");

    while (base<.5)
        return 0;

    if(base>100) 
        printf("Invalid Input\n");

    while(base>100)
        return 0;

    printf("Please enter the value of height of the triangle:\n");
    scanf("%f", &height);

    if(height<1)
        printf("Invalid Input\n");

    while(height<1)
        return 0;

    if(height>75)
        printf("Invalid Input\n");

    while (height>75)
        return 0;

    area = base * height/2;

    printf("The area of the triangle for base:  %f and height:  %f is %f \n", base,
            height , area );

    return 0;
}

3 个答案:

答案 0 :(得分:2)

您无法阻止用户输入他或她想要的内容,但您可以使用scanf的返回值来决定是否输入了有效值,并提示用户输入正确的内容:

float base;
do {
    printf("Please enter the value of base of the triangle: \n");
} while (scanf ("%f", &base) != 1 || base < .5 || base > 100);

此循环将继续,直到满足所有三个条件:

  • scanf只返回了一个项目,
  • scanf提供的值大于或等于0.5
  • scanf提供的值小于或等于100

答案 1 :(得分:0)

scanf返回已匹配且已成功填充值的变量数。 只是做:

int result = scanf ("%f", &base);
if(result != 1)
{
    ...//handle error
}

答案 2 :(得分:0)

我认为您可以按字符阅读输入字符,然后检查它是否为数字,如果您没有显示错误消息。

#include <stdio.h>
 #include <math.h>


int main(void)
{
    float base, height;
    float area;



printf("Please enter the value of base of the triangle: \n");
char c='\n';
char success=0;
base=0;
char dot=0;
do{
scanf ("%c", &c);
if((c>=48)&&(c<=57)){
  if(dot==0)
    base=base*10+(c-48);
  else{
    base+=(c-48)/dot;
    dot*=10;
  }
}
else
 if((c=='.')&&(dot==0))
     dot=10;
 else
   if(c!='\n')
     success=1;

}while((c!='\n')&&(succes==0));


if(success!=0) return -1; //error we break out
if(base<.5) 
printf("Invalid Input\n");
while (base<.5)
return 0;


if(base>100) 
printf("Invalid Input\n");
while(base>100)
    return 0;


printf("Please enter the value of height of the triangle:\n");
c='\n';
 success=0;
height=0;
 dot=0;
do{
scanf ("%c", &c);
if((c>=48)&&(c<=57)){
  if(dot==0)
    height=height*10+(c-48);
  else{
    height+=(c-48)/dot;
    dot*=10;
  }
}
else
 if((c=='.')&&(dot==0))//check if is the first time the user insert a dot
     dot=10;
 else
   if(c!='\n')
     success=1;

}while((c!='\n')&&(succes==0));


if(success!=0) return -1; //error we break out


if(height<1)
printf("Invalid Input\n");

while(height<1)
return 0;

if(height>75)
printf("Invalid Input\n");

while (height>75)
return 0;

area = base * height/2;

printf("The area of the triangle for base:  %f and height:  %f is %f \n", base,
height , area );

return 0;


}