読み込んでいるテキスト ファイルは、以下のコードのコメント セクションにあります。思ったように仕事に就け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;
}