在C中搜索.csv文件 [英] Search in a .csv file in C
本文介绍了在C中搜索.csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用C做一个项目,我需要在其中搜索.csv文件.但是,程序中存在一些错误,我找不到它们.独立于我输入的城市(文件中存在),唯一出现的是"ERROR". 有谁可以帮助我吗?谢谢! (对不起,我的英语不是我的母语……)
I'm doing a project in C, in which I need to search in a .csv file. However, there are some mistakes in the program, and I can't find them. Independently of the city I enter (existing in the file), the only thing that appears is "ERROR". Can someone help me, please? Thanks! (Sorry for my English, it isn't my first language...)
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);
}
}
推荐答案
您好,Stephen Docy是正确的.他已经指出了你的错误.我刚刚修改了您的代码,以使其适合您.
Hi Stephen Docy is right. Already he pointed out your mistake. I have just modified your code so that it should work for you.
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);
}
这篇关于在C中搜索.csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文