首页 > 解决方案 > 双面印刷-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;
}

这是我调用函数的代码。

标签: cnullreturnprintf

解决方案


这就是问题所在:

// Some code

else if (menu == 4) 
{
    loadFlights(flightDatabase, totalflights, f);
    totalflights = loadFlights(flightDatabase, totalflights,f);
}

这是两次连续调用,loadFlights而第一次调用没有捕获返回值。您可以摆脱第一个,它应该按照您期望的方式运行。

此外,我看到一个问题:

while (menu != 5)

此时,menu未初始化,将持有一个随机值。您可能希望将其初始化为零或 5 或任何对该数据类型合法的值。

我尝试在读取错误周围放置一个 if 语句...

这些是补丁作品,拥有真的很危险。它通常期望调试代码并找出确切的问题,而不是添加补丁来掩盖现有的错误。


推荐阅读