【问题标题】:Looping a switch with for loop in C在 C 中使用 for 循环循环开关
【发布时间】:2020-07-06 05:27:50
【问题描述】:

我的 for 循环开关无法工作。如果用户键入除“y”、“Y”、“n”、“N”以外的字母,我希望程序重复该问题。有人可以帮我解决吗?

#include <stdio.h>

int main(void) {

  int flag = 0;
  char mstatus;

  printf("Are you married?\n");
  scanf(" %c", &mstatus);

  for (; flag == 1;) {
    printf("Are you married?\n");
    scanf(" %c", &mstatus);
    switch (mstatus) {
    case 'y':
    case 'Y':
      printf("You have answer yes for married");
      flag = 1;
      break;
    case 'n':
    case 'N':
      printf("You have answer no for married");
      flag = 1;
      break;
    default:
      printf("please re-enter a valid answer");
      scanf(" %c", &mstatus);
    }
  }
  return 0;
}

【问题讨论】:

  • 循环未启动。将标志初始化为 1
  • while 循环或do...while 循环会更清晰。你的条件不对。使用for(; flag == 0; ) 或更好的while(flag == 0)do { ... } while(flag == 0);
  • 只需将flag == 1 更改为flag != 1
  • 使用调试器并单步执行代码。你会很快找到你所有的错误。调试是编码的重要组成部分。
  • 测试出来的错误,为什么循环前的第一对printf/scanf?不使用第一个 scanf 输入。另外为什么 scanf 进入 switch 的“默认”情况?未使用输入字符

标签: c for-loop switch-statement


【解决方案1】:

你的代码有几个问题

第一对

printf("Are you married?\n");
scanf(" %c", &mstatus);

因为你不使用阅读答案而一无所获,删除这些行

for (; flag == 1;) {

您立即退出循环,因为您将flag初始化为0,这与您更改flag值的方式不一致,将其与0而不是1进行比较

default:
  printf("please re-enter a valid answer");
  scanf(" %c", &mstatus);

scanf 必须删除,因为您不使用阅读答案

除此之外,因为您想至少执行一次循环来询问并管理它,所以使用 do ...while

打印内容时还要添加最后一个换行符

例子:

#include <stdio.h>

int main(void) {

  int flag = 0;

  do {
    char mstatus;

    printf("Are you married?\n");
    scanf(" %c", &mstatus);

    switch (mstatus) {
    case 'y':
    case 'Y':
      printf("You have answer yes for married\n");
      flag = 1;
      break;
    case 'n':
    case 'N':
      printf("You have answer no for married\n");
      flag = 1;
      break;
    default:
      printf("please re-enter a valid answer\n");
    }
  } while (flag == 0);

  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -Wall d.c
pi@raspberrypi:/tmp $ ./a.out
Are you married?
a
please re-enter a valid answer
Are you married?
y
You have answer yes for married
pi@raspberrypi:/tmp $ ./a.out
Are you married?
d
please re-enter a valid answer
Are you married?
N
You have answer no for married
pi@raspberrypi:/tmp $ 

当然,在您的情况下,循环之后没有任何内容,因此您还可以简化所有删除 flag 及其管理并将前两个 break 替换为 return 0,当然这种情况下循环可以是for(;;)或者while(1)

可能请输入一个有效的答案请重新输入一个有效的答案更好,因为根据定义,用户永远不会输入一个有效的答案,所以他不能重新-输入一个

【讨论】:

  • 谢谢!!现在我知道如何使用带开关的 do while 循环了!
猜你喜欢
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 2013-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多