如果用户输入错误,则将一段代码循环回代码中的某个点

时间:2018-04-30 02:02:38

标签: c loops scanf

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


#define MAX_FLIGHTCODE_LEN 6



int main()
{
int choice;
int monthd;
int dayd;
int hourd;
int minuted;
int montha;
int daya; 
int houra; 
int minutea;
char flightcode[MAX_FLIGHTCODE_LEN+1];
char arrival_city [MAX_CITYCODE_LEN+1];
flight_t flights [MAX_NUM_FLIGHTS];
do
{
printf("1. add a flight\n");
printf("2. display all flights to a destination\n");
printf("3. save the flights to the database file\n");
printf("4. load the flights from the database file\n");
printf("5. exit the program\n");
printf("Enter choice (number between 1-5)>\n");
scanf("%d",&choice);

switch (choice)
{
 case (1):
      printf("Enter the flight code: \n");
      scanf("%s",&flightcode[MAX_FLIGHTCODE_LEN+1]);
      printf("Enter departure info for the flight leaving SYD.\n");
      printf("Enter month, date, hour and minute separated by spaces>\n");
      scanf("%d %d %d %d",monthd,dayd,hourd,minuted);
      continue;
 case (2):
     printf("yay");
      continue;
 case (3):
     printf("Goodbye\n");
     continue;
     default: printf("Wrong Choice. Enter again\n");
                break;
 }

 } while (choice != 3);
 return 0;
 }

在案例1中,我需要程序循环回到printf(&#34;输入以空格分隔的月,日,小时和分钟&gt; \ n&#34;);如果用户输入scanf的无意义值(&#34;%d%d%d%d&#34;,月,日,小时,分钟);谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

do {
  //the stuff in case 1
} while(nonsense);

这就是我通常做的事情。语法可能与您有所不同,但想法是案例1运行一次然后重复,只要有无意义。 只需在您的案例中运行1并将语法更改为您的语言。希望它有所帮助!