【问题标题】:How to repeat a menu (ask for user input again) after switch got a wrong input character切换输入字符错误后如何重复菜单(再次要求用户输入)
【发布时间】:2014-10-24 01:38:41
【问题描述】:

我有一个菜单,其中一个选项是退出程序,但如果用户键入了 1 2 3 4 5 6 以外的字符,它仍然会退出程序或停止运行它。我希望在输入错误字符后菜单再次出现并且用户可以再次键入。如果用户无限地输入错误的字符,我希望这种情况无限地发生。 非常感谢!

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
  char opcao;


  printf("1 - \n"); 
  printf("2 -\n"); 
  printf("3 - \n"); 
  printf("4 - \n"); 
  printf("5 - \n"); 
  printf("6 - Terminar programa\n");  
  printf("Introduza a sua opcao:\n");
  scanf("%c",&opcao);

      switch(opcao){
    case'1':
      printf("Funcionalidade nao disponivel.");
      break;
    case'2':
      printf("Funcionalidade nao disponivel.");
      break;
    case'3':
      printf("Funcionalidade nao disponivel.");
      break;
    case'4':
      printf("Funcionalidade nao disponivel.");
      break;
    case'5':
      printf("Funcionalidade nao disponivel.");
      break;
    case'6':
      exit(0);
    default:
      printf("invalid input, please type again"); // this is what I want, but how?(now it would present the menu again...
      break;
      }

  return 0; 
}

【问题讨论】:

  • 做...while循环? C 书籍中的第一件事
  • 提示:用户可能多次输入错误,您需要继续显示菜单。所以你想把你的 switch 语句放在一个循环中。输入正确时退出循环。
  • 一个做while循环? @SteveWellens??

标签: c menu switch-statement


【解决方案1】:

使用do...while 循环,使您的代码如下所示:

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
  char opcao;


  printf("1 - \n"); 
  printf("2 -\n"); 
  printf("3 - \n"); 
  printf("4 - \n"); 
  printf("5 - \n"); 
  printf("6 - Terminar programa\n");  
  printf("Introduza a sua opcao:\n");
  do{ //loop
  scanf(" %c",&opcao); //discards blanks and reads the first non-whitespace character

      switch(opcao){
    case'1': 
    case'2':
    case'3':
    case'4':
    case'5':
  printf("Funcionalidade nao disponivel.");
   break;
    case'6':
      exit(0);
    default:
      printf("invalid input, please type again:"); // this is what I want, but how?(now it would present the menu again...
      }
  }while(opcao<'1' ||opcao>'6'); //loop until `opcao` less than '1' or greater than '6'

  return 0; 
}

【讨论】:

  • 如果我输入错误,输出会说句子无效输入,请再次输入:两次-
  • @LeonardoNunes ,您没有正确复制我的代码。将我的scanf 替换为您的scanf 并看到魔法!
【解决方案2】:

我在这里给出了一个示例代码。您可以根据需要对其进行增强

#include <string.h>
int main (){
    char c, q=1;
    while ( q ){
        c=getchar ();
        switch (c){
            case '1':{} break;
            case '2': {printf ("quit the menu\n");q=0;}break;
        }
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    相关资源
    最近更新 更多