簡體   English   中英

切換輸入錯誤字符后如何重復菜單(再次詢問用戶輸入)

[英]How to repeat a menu (ask for user input again) after switch got a wrong input character

我有一個菜單,其中一個選項是退出程序,但是如果用戶鍵入的字符不是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; 
}

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

我在這里給出了示例代碼。 您可以根據需要對其進行增強

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM