c - yes 或 no 退出 switch 语句

标签 c

是否可以创建调用 yes 或 no 函数来退出 switch 语句。如果 (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);
}

最佳答案

考虑以下 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");
    }
  }
}

如果输入yes,返回值1,如果输入no,返回值0 .考虑到这一点,在 switch 语句的 case 0 代码块中,可以捕获此函数的返回值,然后可以使用它来打破循环或者什么都不做。例如:

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;
}

关于c - yes 或 no 退出 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42877495/

相关文章:

c++ - 以编程方式获取环回接口(interface)/C++

android - 在 Android 5/Lollipop 上打印 C 堆栈跟踪

c - memcpy--memcpy 后内核崩溃

c - 无需 X-Forwarding 的真正远程编辑,使用 Vim 等

c - matlab 中 mex 函数的安全、快速 CFLAGS

c - 如何从控制台输入数字

C 所有值都随指针改变

使用随机指针克隆二叉树

c - 是否可以覆盖目标模块(gcc、ld、x86、objcopy)中的静态函数?

c - 在 C 中用 jansson 解析 JSON