Hi,
Thank you for your help, problem solve.
Now I want to ask user to enter a city name to see if in the file. If it is print its population.
The problem is there are two city name with similar length, my program can't disguish between the two cities and print them on screen.
I have use if(strncmp(city, cityName, strlen(cityName)==0) to compare the string.
--------------------------------
Part of input file:
Code:
Abidjan,C?te d'Ivoir
*
*
St. Louis,USA,2825000
St. Petersburg,Russia,4775000
Stockholm,Sweden,1910000
*
*
----------------------------------
My code
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/*Purpose: get city name from user
See if cityname is in the file.
If it is print population
Problem occur when type in a city there are two cities with similar name
it will print both out.
e.g INPUT : St. Louis
OUTPUT: St. Petersburg
*/
int main()
{
FILE *fp=fopen("e:\\city.txt", "r");
char city[256];
char country[256];
int pop;
char cityName[256];
int i;
printf("Which city do you want to search for? ");
scanf("%s", cityName);
/*Read three items per line*/
while(fscanf(fp," %[^,], %[^,], %d", city, country, &pop)==3)
{
/*Compare the whole cityName[] with city[] in the file.*/
if(strncmp(city, cityName,strlen(cityName))==0)
{
printf("%s %s %d\n",city, country, pop);
}
}
fclose(fp);
fflush(stdin);
getchar();
return 0;
}
---------------
Is my logic correct?
Are there any method to solve the problem?
-----------------------
OUTPUT
Code:
Which city do you want to search for? St. Louis
St. Louis USA 2825000
St. Petersburg Russia 4775000
Thanks
Henry