是或否退出switch语句

时间:2017-03-18 17:22:26

标签: c

是否可以创建yes或no函数来调用退出switch语句。 if(y)es被击中它会退出。如果击中(n)o,它将循环回到开关的选项。如果是这样,将如何做到这一点。这是我到目前为止所做的。

我希望这有助于澄清我想要做的事情

int yes_no(void) {

    scanf("%d", &option);

    while (option == 'y' || option == 'Y' || option == 'n' || option == 'N') {
        if (option == 'y' || option == 'Y') {
            return 1;
        } else
        if (option == 'n' || option == 'N') {
            return 0;
        } else {
            printf("Only (Y)es or (N)o are acceptable");
        }
    }
}

int main(void) {
    int select;

    do {
        printf("0 exit");
        printf("1 hello");

        scanf("%d", &select);

        switch (select) {
          case 0:
            printf("Exit the program? (Y)es or (N)o :");
            yes_no(); // if (n)o is hit it will loop back to the menu
            break;
          case 1:
            printf("hello how r u doing");
            break;
          default:
            printf("not accepted number");
        }
    } while (select != 0);
}

3 个答案:

答案 0 :(得分:2)

考虑以下yes_no函数。

int yes_no() {
  char option;

  while (1) {
    printf("(y/n): ");
    if (scanf(" %c", &option) != 1) {
      printf("Error occurred while reading option.\n");
      continue;
    }

    if (option == 'y' || option == 'Y') {
      return 1;
    } else if (option == 'n' || option == 'N') {
      return 0;
    } else {
      printf("Only (y)es or (n)o are acceptable.\n");
    }
  }
}

如果输入1,则返回值为yes; 0时返回值为no。考虑到这一点,在case 0语句的switch代码块中,可以捕获此函数的返回值,然后可以使用该函数来中断循环或不执行任何操作。例如:

int main(void) {
  int select;
  int continue_loop = 1;

  printf("Press 0 to exit\n");
  printf("Press 1 for hello\n\n");

  while (continue_loop) {
    printf("(0/1): ");
    if (scanf(" %d", &select) != 1) {
      printf("Error occurred while reading number.\n");
      continue;
    }

    switch (select) {
      case 0:
        printf("Exit the program? (y)es or (n)o;\n");
        int make_sure = yes_no();  // yes_no() returns 1 if 'yes', and 0 if 'no'
        // If 'yes', break while loop by setting continue_loop to 0.
        // Do nothing in case of 'no'
        if (make_sure == 1) {
          continue_loop = 0;
        }
        break;
      case 1:
        printf("Hello, how are you doing?\n");
        break;
      default:
        printf("Number not accepted.\n");
    }
  }

  return 0;
}

答案 1 :(得分:0)

如果我正确地回答你的问题,这应该可以胜任:

int yes_or_no()
{
  do
  {
    char option = 0;
    scanf(" %c", &option);
    if (option == 'y' || option == 'Y')
      return 1;
    if (option == 'n' || option == 'N')
      return 0;
    printf("Only (Y)es or (N)o are acceptable");
  }
  while( 1 );
}

答案 2 :(得分:0)

使用开关,您可以更好地执行代码:

int yes_no(void) {
scanf("%d", &option);
while (1){
switch(option){
case 'y':
case 'Y':
return 1;
case 'n':
case 'N':
return 0;
default:
printf("invalid input.try again");
scanf("%d", &option);
}
}
}