神秘博客

自行设计函数判断输入内容是否正确

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define ANSWER "Grant"
#define SIZE 40

char *s_gets(char *st, int n);
bool compare(char *ar, int n);

int main()
{
  char try[SIZE];
  bool n;

  puts("谁葬在格兰特的墓里?");
  s_gets(try, SIZE);
  n = compare(try, strlen(try));
  while (!n || try[0] == '\0')
  {
    puts("不, 那是错的. 再试一次.");
    s_gets(try, SIZE);
    n = compare(try, strlen(try));
  }
  
  puts("这是正确的!");

  system("pause");
  return 0;
}
char *s_gets(char *st, int n)
{
  char *ret_val;
  int i = 0;

  ret_val = fgets(st, n, stdin);
  if (ret_val)
  {
    while (st[i] != '\n'&&st[i] != '\0')
      i++;
    if (st[i] == '\n')
      st[i] = '\0';
    else
      while (getchar() != '\n')
        continue;
  }

  return ret_val;
}

bool compare(char *ar, int n)
{
  int i;
  char name[] = "Grant";
  bool b = true;

  for (i = 0; i < n; i++)
  {
    if (ar[i] != name[i])
      b = false;
  }

  return b;
}

 

版权说明:
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注

觉得文章有用就请我吃包辣条吧

微信扫一扫打赏