【问题标题】:Making a piece of code loop back to a certain point in the code if wrong input from user如果用户输入错误,则使一段代码循环回代码中的某个点
【发布时间】:2018-04-30 02:02:37
【问题描述】:
#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,minuted) 输入了无意义的值;感谢您的帮助

【问题讨论】:

  • scanf("%s",&amp;flightcode[MAX_FLIGHTCODE_LEN+1]); 的每个部分都是错误的。不应使用%s,因为它不限制输入量(导致缓冲区溢出)。 &amp;flightcode[MAX_FLIGHTCODE_LEN+1] 不指向可以放置输入的存储;它指向flightcode 数组末尾的一个元素。最后,scanf 不应该用于用户输入(最好用fgets 或类似的方式读取整行,然后再解析它们)。如果您确实使用了scanf,请始终检查其返回值。
  • 好的,所以我现在已经修复了 scanf,当我尝试输入月、日、小时和分钟时,程序仍然崩溃。

标签: c loops scanf


【解决方案1】:
do {
  //the stuff in case 1
} while(nonsense);

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

【讨论】:

  • 案例(1):printf("输入航班代码:\n"); scanf("%s",&flightcode[MAX_FLIGHTCODE_LEN+1]); printf("输入离开悉尼的航班的出发信息。\n"); do{ printf("请输入月份、日期、小时和分钟,以空格分隔>\n"); scanf("%d %d %d %d",monthd,dayd,hourd,minuted); }while(12
  • 每当我输入无效输入时它就会崩溃。不知道为什么。
  • 或者即使我输入了有效的输入
  • 是什么语言?我会尝试自己运行它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2013-05-23
相关资源
最近更新 更多