如何解决我有一个程序可以输入一个名为 search 的字符串,它是目标,如果“搜索”在那里,我想在 csv 文件中搜索
#include <stdio.h>
#include <string.h>
void myfgets(char str[],int n);
int main(int argc,char** argv)
{
if (argc < 2)
{
printf("Usage: csv <csv file path>\n");
return 1;
}
else
{
char ch = ' ',search[100],dh = ' ';
int row = 1;
printf("Enter value to search: ");
myfgets(search,100);
FILE* fileRead = fopen(argv[1],"r");
if (fileRead == NULL)
{
printf("Error opening the file!\n");
return 1;
}
while ((ch = (char)fgetc(fileRead)) != EOF)
{
char str[100];
int i = 0,pos = ftell(fileRead);
while ((dh = (char)fgetc(fileRead)) != ',')
{
str[i] = dh;
i++;
}
fseek(fileRead,pos + 1,SEEK_SET);
if (strstr("\n",str) != NULL)
{
row++;
}
if (strstr(search,str) != NULL)
{
printf("Value was found in row: %d\n",row);
break;
}
}
}
getchar();
return 0;
}
/*
Function will perform the fgets command and also remove the newline
that might be at the end of the string - a kNown issue with fgets.
input: the buffer to read into,the number of chars to read
*/
void myfgets(char* str,int n)
{
fgets(str,n,stdin);
str[strcspn(str,"\n")] = 0;
}
在第 39 行,我收到一个错误,但我不知道为什么我似乎一切都很好 我试图遍历行并用“,”分割它们,所以我可以检查搜索 == 到它但它不是 wokring 我使用函数 strstr 将 2 个字符串相互比较它工作正常,但唯一的问题是在 dh 我在 dh 之后做了 fseek,所以我不会在 ch 循环中写错地方
解决方法
您忘记终止字符串。
while ((dh = (char)fgetc(fileRead)) != ',')
{
str[i] = dh;
i++;
}
str[i] = '\0'; /* add this to terminate the string */
另外看起来 if (strstr(search,str) != NULL)
应该是 if (strstr(str,search) != NULL)
来搜索要从文件内容中搜索的值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。