c - 双面印刷-C
问题描述
我正在从文件中读取,但是如果它不存在意味着打印“读取错误”,但由于某种原因,它会打印两次读取错误,我不知道为什么
int loadFlights(char flightDatabase[50], int totalflights, flight_t f[MAX_NUM_FLIGHTS])
{
int counter;
FILE *fp;
fp = fopen("database.txt", "r");
if(fp == NULL) { /************************statement with problem*/
printf("Read error\n");
return 1;
}
fscanf(fp, "%d", &totalflights);
if (totalflights > 5) {
totalflights = 5;
}
for(counter = 0; counter <= totalflights-1; counter++)
{
fscanf(fp, "%s %d %d %d %d %s %d %d %d %d", f[counter].flightcode,
&f[counter].departure_dt.month, &f[counter].departure_dt.date,
&f[counter].departure_dt.hour, &f[counter].departure_dt.minute,
f[counter].arrival_citycode, &f[counter].arrival_dt.month,
&f[counter].arrival_dt.date, &f[counter].arrival_dt.hour,
&f[counter].arrival_dt.minute);
}
fclose(fp);
return totalflights;
}
我已经尝试if
在 Read Error if 语句周围放置一个语句,如果它已经被打印,则不再打印,但它似乎仍在打印。
int main(void)
{
flight_t f[MAX_NUM_FLIGHTS];
int totalflights = 0, menu;
char flightDatabase[50] = "database.txt";
while (menu != 5)
{
print_Menu();
scanf("%d", &menu);
while ((menu < 0) || (menu > 5)) {
printf("Invalid choice\n");
print_Menu();
scanf("%d", &menu);
}
if (menu == 1)
{
addFlight(f, totalflights);
totalflights++;
}
else if (menu == 2)
{
displayFlight(f, totalflights);
}
else if (menu == 3)
{
saveFlight(f, flightDatabase, totalflights);
}
else if (menu == 4)
{
loadFlights(flightDatabase, totalflights, f);
totalflights = loadFlights(flightDatabase, totalflights,f);
}
}
return 0;
}
这是我调用函数的代码。
解决方案
这就是问题所在:
// Some code
else if (menu == 4)
{
loadFlights(flightDatabase, totalflights, f);
totalflights = loadFlights(flightDatabase, totalflights,f);
}
这是两次连续调用,loadFlights
而第一次调用没有捕获返回值。您可以摆脱第一个,它应该按照您期望的方式运行。
此外,我看到一个问题:
while (menu != 5)
此时,menu
未初始化,将持有一个随机值。您可能希望将其初始化为零或 5 或任何对该数据类型合法的值。
我尝试在读取错误周围放置一个 if 语句...
这些是补丁作品,拥有真的很危险。它通常期望调试代码并找出确切的问题,而不是添加补丁来掩盖现有的错误。
推荐阅读
- dataframe - PySpark - 使用正则表达式反透视数据框
- node.js - Lambda 函数 errorMessage”:“无法读取未定义的属性 'bucket'
- vmware - VMWare:关于快照:它们通常会占用多少% 的磁盘空间源VM?他们是否习惯于降级软件?
- flutter - 如何通过向下拖动来关闭小部件
- xml - SpringBoot:获取方法不产生预期的 XML 元素
- bots - DiscordAPIError:未知角色
- xpath - Scrapy:如何从通过ajax加载的页面中提取数据?
- python - 制作提取帧的视频时出错
- python - 我正在尝试编写代码以保存到 excel 但它不断覆盖
- azure-devops - 无法删除 Azure Dev Ops 中的测试计划/套件