2013-07-02 61 views
-4

我正在加載的文本文件位於下面代碼的註釋部分。我無法讓sscanf()像我認爲應該那樣工作。必須有一種方式,幾乎是這個優雅而不必使用指針,通過每個角色中去,爲循環等解析C中的管道分隔線條

//Apex City Hotel|4|61 Grassmarket|Edinburgh|EH1 
//Hilton Edinburgh Airport|4|Edinburgh International Airport|Edinburgh|EH12 
//Novotel Edinburgh Centre|4|80 Lauriston Place|Edinburgh|EH3 
//Premier Inn Haymarket|3|1 Morrison Link|Edinburgh|EH3 
//Premier Inn Lauriston Place|3|82 Lauriston Place|Edinburgh|EH3 
//Premier Inn Leith|3|51-53 Newhaven Place - Leith|Edinburgh|EH6 
//Sheraton Grand Hotel & Spa|5|1 Festival Square|Edinburgh|EH3 
//The Caledonian|5|Princess Street|Edinburgh|EH1 
//The Glasshouse|5|2 Greenside Place|Edinburgh|EH1 
//The Hilton Edinburgh Grosvenor|4|Grosvenor Street|Haymarket|Edinburgh|EH12 

代碼:

int main(void) 
{ 
    char inputArray[NUM_OF_CHARACTERS]; 
    FILE *fp = fopen("OpenChampionshipHotels.txt", "r"); 
    fgets(inputArray, NUM_OF_CHARACTERS, fp);  

    if (fp == NULL) 
    { 
     printf("Error Reading File\n"); 
     exit(1); 
    } 

    // copy lines from text file to array 
    char hotelName[lineCount][NUM_OF_CHARACTERS]; 
    char hotelRating[lineCount][NUM_OF_CHARACTERS]; 
    char hotelStreetAddress[lineCount][NUM_OF_CHARACTERS]; 
    char hotelCity[lineCount][NUM_OF_CHARACTERS]; 
    char hotelPostalCode[lineCount][NUM_OF_CHARACTERS]; 

    lineCount = 0; 
    while(fgets(inputArray, sizeof(inputArray), fp) != NULL) 
    { 
     sscanf(inputArray, "%[^|]|%[^|]|%[^|]|%[^|]|%s", 
       hotelName[lineCount], 
       hotelRating[lineCount], 
       hotelStreetAddress[lineCount], 
       hotelCity[lineCount], 
       hotelPostalCode[lineCount]); 

     printf("%s\n", hotelName[lineCount]); 
     printf("%s\n", hotelRating[lineCount]); 
     printf("%s\n", hotelStreetAddress[lineCount]); 
     printf("%s\n", hotelCity[lineCount]); 
     printf("%s\n", hotelPostalCode[lineCount]); 

     lineCount++; 
    } 
    fclose(fp); 

    return 0; 
} 
+3

*「我無法讓sscanf()像我認爲應該那樣工作。」*您認爲它應該如何工作?你得到了什麼結果?你有什麼試圖調試或解決問題? (詢問** 101 **的問題) – abelenky

+0

'「錯誤讀取文件」是無用錯誤消息的典型示例。包括文件名和原因! 'man perror' –

+0

請注意,您應該檢查'sscanf()'的返回值以確保該行的格式正確。如果您獲得完整的郵編(EH3 9JX),則需要修正'%s'轉換規範。 –

回答

2

您使用的sscanf()有罰款。你的問題只是你使用lineCount來聲明你的數組的大小,這大概是一個全局變量,因此在那一點上是零。

定義一個常量NUM_OF_LINES並使用它:

char hotelName[NUM_OF_LINES][NUM_OF_CHARACTERS]; 
char hotelRating[NUM_OF_LINES][NUM_OF_CHARACTERS]; 
char hotelStreetAddress[NUM_OF_LINES][NUM_OF_CHARACTERS]; 
char hotelCity[NUM_OF_LINES][NUM_OF_CHARACTERS]; 
char hotelPostalCode[NUM_OF_LINES][NUM_OF_CHARACTERS]; 

(您也應該檢查返回sscanf() 5,搭上線,而不領域的權數,並添加lineCount < NUM_OF_LINESwhile()條件)。