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

标签 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("输入月份、日期、小时和分钟,并用空格分隔>\n");如果用户为 scanf("%d %d %d %d",monthd,dayd,hourd,mined) 输入无意义的值;感谢您的帮助

最佳答案

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

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

关于c - 如果用户输入错误,则使一段代码循环回到代码中的某个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50093127/

相关文章:

c - 为什么我不能修改 c 中的字符串文字?

c - 单元测试: CUnit

c - C 中 1 的无效写入大小

python - 哪个 Python 模块可以在 while 循环中监控 3 个按键组合?

python - "Pythonic"for 循环整数 0 到 k-1 除了 i

c - 如何在结构中正确使用 fgets?

c++ - 从 SID 创建用户 token ,在用户上下文中扩展环境变量

python - 我怎样才能用kv语言动态地制作很多按钮?

c - 使用 scanf_s 仅取整数时如何进行错误检查?

c - scanf() 不显示在屏幕上