我正在加载的文本文件位于下面代码的注释部分。我无法像我认为的那样让sscanf()
工作。必须有一种几乎优雅的方式,而不必使用指针,for循环等来遍历每个角色。
//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;
}
答案 0 :(得分: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_LINES
添加到while()
条件。)