我正在尝试编写一个用户进入城市的控制台应用程序,然后程序在typedef结构中查找城市名称并继续显示城市的纬度和经度坐标。我没有显示该程序的错误,但似乎每次我进入一个城市并按下输入控制台应用程序将显示未找到的城市,然后关闭。以下是typdef结构中的一些城市的代码(完整结构包含200个变量)。
#include <stdio.h>
#include <string.h>
#define MAX_CITY_LEN 35
typedef struct {
char name[MAX_CITY_LEN];
float latitude;
float longitude;
} PLACE_T;
PLACE_T places[] =
{{"Aberdeen,Scotland",57.15,-2.15},
{"Adelaide,Australia",-34.92,138.6},
{"Albany,NY,USA",42.67,-73.75},
{"Albuquerque,NM,USA",35.08,-106.65},
{"Algiers,Algeria",36.83,3.0},
{"Amarillo,TX,USA",35.18,-101.83},
{"Amsterdam,Netherlands",52.37,4.88},
{"Anchorage,AK,USA",61.22,-149.9},
{"Ankara,Turkey",39.92,32.92},
{"Asuncion,Paraguay",-25.25,-57.67},
{"Athens,Greece",37.97,23.72},
{"Atlanta,GA,USA",33.75,-84.38},
{"Auckland,New Zealand",-36.87,174.75},
{"",999,999}};
int main()
{
int j;
int found=0;
char city[MAX_CITY_LEN];
int citySize=(sizeof(places)/sizeof(places[0]));
printf("Please Enter the Name of a City: \n");
scanf_s("%s", &city, MAX_CITY_LEN,stdin);
city[strlen(city)-1]='\0';
for(j=0;j<citySize;j++)
{
if(strcmp(city,places[j].name)==0)
{
found=1;
printf("lat = %f, long = %f",places[j].latitude,places[j].longitude);
break;
}
}
if(!found)
printf("City not found");
return 0;
}
谢谢!
答案 0 :(得分:0)
试试这个
int found=0;
char city[MAX_CITY_LEN];
int citySize=(sizeof(places)/sizeof(places[0]));
int j, len;
printf("Please Enter the Name of a City: \n");
scanf_s("%34s", city, MAX_CITY_LEN);
len = strlen(city);
for(j=0;j<citySize;j++){
if(strncmp(city, places[j].name, len)==0 && places[j].name[len]==','){
found=1;
printf("lat = %f, long = %f",places[j].latitude,places[j].longitude);
break;
}
}
if(!found)
printf("City not found");