我正在創建一些動態字串,使用的函式使用 fgets 從用戶那里獲取輸入。但是,當我試圖讓機場的名字第一次,這只是“跳過”自動把與fgets\n在temp繼續的功能。所有其他輸入都是正確的,而不是第一個。
Please enter name of Airport:
這里只是跳過輸入程序,直接列印“輸入地址”:
----------Please enter the address-------------
Please enter name of country:
Please enter name of city:
int initAirport(Airport* airportP)
{
airportP->nameOfAirPort = createDynamicString("Please enter name of Airport:\n");
printf("----------Please enter address-------------\n");
airportP->country = createDynamicString("Please enter name of country:\n");
airportP->city = createDynamicString("Please enter name of city:\n");
airportP->address = createDynamicString(" Please enter name of Address:\n");
printf("Please enter house number:\n");
scanf("%d",&(airportP->houseNumber));
return 1;
}
char* createDynamicString(const char* msg)
{
char* str;
char temp[254];
printf(msg);
fgets(temp,254,stdin);
str = (char*)malloc((strlen(temp) 1) * sizeof(char));
if (!str)
return NULL;
strcpy(str, temp);
//str[strlen(str) - 1] = 0;
return str;
}
#pragma once
#define MAX 254
typedef struct
{
char* nameOfAirPort;
char* country;
char* city;
char* address;
int houseNumber;
} Airport;
int initAirport(Airport* pNameOfAirport);
void addNumberSignToString(char* stringOfNumberSign);
void printNameOfAirport(const Airport* pNameOfAirport);
int isSameAirport(Airport* airport1P, Airport* airport2P);
int isAirportName(Airport* airportP, char* airportName);
void freeAirport(Airport* airportP);
uj5u.com熱心網友回復:
scanf()將換行符留在緩沖區中,fgets()然后在用戶有機會輸入任何內容之前將其取出并退出。
你必須在之后清除緩沖區 scanf()
void clearInputBuffer(void)
{
int c;
do {
c = getchar();
} while (c != '\n' && c != EOF);
}
uj5u.com熱心網友回復:
檢查這個問題:scanf() 在緩沖區中留下換行符
使用scanf()函式后,在緩沖區中scanf()留下一個換行符\n。然后,initAirport函式中的 fgets()出現,它需要換行符,并且您無法輸入。但這只會發生一次,因為下次您呼叫createDynamicStringfunction 時,您將使用fgets()function 而不是scanf().
您可以在第一次呼叫scanf()函式后輸入此代碼示例,您所說的函式存在并詢問用戶是否要添加機場,然后呼叫另一個函式initAirport():
while (getchar() != '\n');
這基本上需要緩沖區中的現有字母,直到遇到換行符為止。在這種情況下,這將過濾掉scanf()留在緩沖區中的換行符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/373382.html
