[英]Double Printing - 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;
}
我試過在Read Error if
語句周圍放一個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語句...
這些是補丁程序,確實很危險。 通常希望調試代碼並找出確切的問題,而不是添加補丁來掩蓋現有的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.