如何防止输入成为某些字符?

时间:2015-12-10 06:28:10

标签: c logic

这是我的一部分代码:我不希望用户输入除了A-Z,a-z,1-9和_之外的其他内容。我不知道自己做错了什么!基本上,如果用户输入的内容不是那些字符,则会输出错误。我一直试图调试这几个小时,我觉得我只是做了更多的东西"凌乱"。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void get_outputfile(char *outname, int count_attempts);

FILE* CreateFile(){
   char name[20];
   char user_decision[1];
   int count_attempts=0;
   for(;;){
      get_outputfile(name, count_attempts);
      FILE *test;
      test = fopen(name,"r");
      if(test!=NULL){
         fclose(test);
         printf("file %s already exists, would you like to overwrite (Y/N)? ",name);
         scanf("%s",user_decision);
      }
      if(user_decision[0]!='Y'&&user_decision[0]!='y'){
         count_attempts=0;
         continue;
      }
      else{
         return fopen(name,"w");
      }
   }
   return 0;
}

void get_outputfile(char *outname, int count_attempts){
   int i;
   printf("Enter the output file name:");
   scanf("%s",outname);
   fgetc(stdin);
   for(i=0;i<strlen(outname);i++){
      if(((outname[i]<'a'||outname[i]>'z')&&(outname[i]<'A'||outname[i]>'Z')&&(outname[i]<'0'||outname[i]>'9'))&&(outname[i]!='_')){
         if (count_attempts>1){
            printf("You have exceeded maximum attempts. Restart the program and try again.\n");
            exit(0);
         }
         count_attempts++;
         printf("file name must be _, a-z, or A-Z\nEnter the output file name:");
         scanf("%s",outname);
         i=0;
      }
   }
   printf("returning..\n");
   return;
}

int main(){
   FILE* afile = CreateFile();
   return 0;
}

1 个答案:

答案 0 :(得分:0)

中的逻辑
  if(((outname[i]<'a'||outname[i]>'z')&&(outname[i]<'A'||outname[i]>'Z')&&(outname[i]<'0'||outname[i]>'9'))&&(outname[i]!='_')){

错了。

我建议创建一个可以简化逻辑并更容易理解的函数。

int isValidCharacter(char c)
{
   return ( (c >= 'a' && c <= 'z') || // Takes care of lower case letters
            (c >= 'A' && c <= 'A') || // Takes care of uppper case letters
            (c >= '0' && c <= '9') || // Takes care of numberss
            c == '_' );               // Takes care of _
}

并将其用作:

  if ( !isValidCharacter(outname[i]) )
  {
     if (count_attempts>1){

     ...