防止C中字符串中的数字输入

时间:2012-11-01 11:33:52

标签: string validation

char name[50];
int valid;

do{
      valid=1;
      printf("Enter name for Salesman: ");
      fgets(name,50,stdin);
      if(!isalpha(*name)) //it will only scan for the first character of string
      {
          printf("Only alphabet is allowed.\n");
          valid=0;
      }
  }while(valid==0);

我希望整个字符串没有任何数字输入。

2 个答案:

答案 0 :(得分:1)

您必须处理整个字符串:

int i = 0;
for (i = 0; i < strlen(name) && i < 50; i++) {
  if (!isalpha(name[i])) {
    valid = 0;
    printf("Please only use alphabetic characters!\n");
    break;
  }
}

答案 1 :(得分:0)

C语言是否支持像java这样的正则表达式?

所以我们可以在java中这样做:

String test= "Any String even if 1 digit is in between";

Pattern p = Pattern.compile("[0-9]+");

Matcher m = p.matcher(test);

if (m.find())
{               
    System.out.println("Numeric is not allowed");
}