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