我在C中做一个项目,我需要在.csv文件中搜索。但是,程序中存在一些错误,我无法找到它们。独立于我输入的城市(存在于文件中),唯一出现的是" ERROR"。 有谁可以帮助我吗?谢谢! (对不起我的英语,这不是我的第一语言......)
int search_date(){
char tem_max[10];
char tem_min[10];
char humidity[10];
char pressure[10];
char town[100];
char city[100];
int i=0;
printf("Enter the name of the town: ");
scanf ("%[^\n]%*c", town);
FILE *stream = fopen("cities2.csv", "r");
char line[1024];
while (fgets(line, 1024, stream))
{
char *tmp = strdup(line);
if (i > 0) {
strcpy(city, strtok(tmp, ",\n"));
strcpy(tem_max, strtok(NULL, ","));
strcpy(tem_min, strtok(NULL, ","));
strcpy(humidity, strtok(NULL, ","));
strcpy(pressure, strtok(NULL, ","));
if (strcmp(city, town) == 0)
{
printf("Town - Maximum temperature - Minimum temperature - Humidity - Pressure\n");
printf("%s - %s - %s - %s - %s\n",city, tem_max, tem_min, humidity, pressure);
}
i++;
free(tmp);
}
else
{
printf("ERROR");
}
fclose(stream);
}
}
答案 0 :(得分:0)
您将i
初始化为0
,然后在增加之前检查它是否大于0
。看看你的代码,我真的不知道i
的目的是什么。即使第一次测试通过,您所做的只是递增i
并继续阅读。也许你试图跳过阅读文件的第一行?
int search_date(){
char tem_max[10];
char tem_min[10];
char humidity[10];
char pressure[10];
char town[100];
char city[100];
int i=0; // <--- i is 0
printf("Enter the name of the town: ");
scanf ("%[^\n]%*c", town);
FILE *stream = fopen("cities2.csv", "r");
char line[1024];
while (fgets(line, 1024, stream))
{
char *tmp = strdup(line);
if (i > 0) { // <--- i is still 0
strcpy(city, strtok(tmp, ",\n"));
strcpy(tem_max, strtok(NULL, ","));
strcpy(tem_min, strtok(NULL, ","));
strcpy(humidity, strtok(NULL, ","));
strcpy(pressure, strtok(NULL, ","));
if (strcmp(city, town) == 0)
{
printf("Town - Maximum temperature - Minimum temperature - Humidity - Pressure\n");
printf("%s - %s - %s - %s - %s\n",city, tem_max, tem_min, humidity, pressure);
}
i++; // <--- now you do i++
free(tmp);
}
else
{
printf("ERROR");
}
fclose(stream);
}
答案 1 :(得分:0)
嗨Stephen Docy是对的。他已经指出了你的错误。我刚刚修改了你的代码,以便它适合你。
int search_date(){
char tem_max[10];
char tem_min[10];
char humidity[10];
char pressure[10];
char town[100];
char city[100];
int i=1; // <--- now i is 1
printf("Enter the name of the town: ");
scanf ("%[^\n]%*c", town);
FILE *stream = fopen("cities2.csv", "r");
char line[1024];
while (fgets(line, 1024, stream))
{
char *tmp = strdup(line);
if (i > 0) { // <--- i is now > 0
strcpy(city, strtok(tmp, ",\n"));
strcpy(tem_max, strtok(NULL, ","));
strcpy(tem_min, strtok(NULL, ","));
strcpy(humidity, strtok(NULL, ","));
strcpy(pressure, strtok(NULL, ","));
if (strcmp(city, town) == 0)
{
printf("Town - Maximum temperature - Minimum temperature - Humidity - Pressure\n");
printf("%s - %s - %s - %s - %s\n",city, tem_max, tem_min, humidity, pressure);
}
i++; // <--- now you do i++
free(tmp);
}
else
{
printf("ERROR");
}
fclose(stream);
}