在C中使用for循环循环开关

问题描述 投票:0回答:1

我无法使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;
}
c for-loop switch-statement
1个回答
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

及其管理的过程,并用return 0
替换前两个break。在这种情况下,循环可以是for(;;)while(1)
可能

请输入一个有效的答案

请重新输入一个有效的答案更好的选择,因为根据定义,用户从不输入有效的答案,因此他无法重新输入一个
© www.soinside.com 2019 - 2024. All rights reserved.