C:如何使我的程序拒绝超过'y'或'n'的单词?

时间:2016-10-02 05:14:09

标签: c char buffer scanf

所以下面的代码只是一个较大程序的一小部分,它本身就可以正常工作:

int main(){

char ansr;
scanf("%c", &ansr);


  while (ansr != 'y' && ansr != 'n'){

  printf("\n\tInvalid answer, Please try again.");
  while(getchar() != '\n');
  scanf("%c", &ansr);
}

if ( ansr == 'y') {
  sleep(1);
  printf("\n\tYou've been warned.......\n\n");
  sleep(3);
  }
else if ( ansr == 'n') {
  printf("\n\tGoodbye then.\n\n");
}

return 0;
}

如您所见,用户输入的任何不以y或n开头的单词将被拒绝,直到有正确答案为止。我怎样才能包含长于字符'y'和'n'的单词,因为任何以y或n开头的字符都会给出是或否的结果?

2 个答案:

答案 0 :(得分:4)

对于此类用例,请勿使用scanf来阅读输入内容。使用fgets逐行读取文本,并使用任何有意义的逻辑处理每一行。

int main()
{
   char answer[LINE_LENGTH];  // #define LINE_LENGTH to a sensible value.
   while ( fgets(answer, LINE_LENGTH, stdin) != NULL )
   {
      // Trim the line of the newline character.
      int len = strlen(answer);
      if ( answer[len-1] == '\n' )
      {
         answer[len-1] = '\0';
      }

      if ( strcmp(answer, "y") == 0 ||
           strcmp(answer, "n") == 0 )
      {
         break;
      }

      printf("\n\tInvalid answer, Please try again.");
   }

   if ( strcmp(answer, "y") == 0)
   {
      sleep(1);
      printf("\n\tYou've been warned.......\n\n");
      sleep(3);
   }
   else if ( strcmp(answer, "n") == 0 )
   {
      printf("\n\tGoodbye then.\n\n");
   }

   return 0;
}

答案 1 :(得分:0)

使用fgets代替getchar,以检索多个字符。