如何解决如何存储除选定行以外的其余行?
在这段代码中,我试图跳过一行。这意味着除从输入身份证号码获取的那一行外,所有行均应存储在数组中。
例如。如果我输入了第一个的ID card number
,则该行应被忽略,其余的行应存储在数组中。或者,如果我输入了第二行,则应该忽略第二行,其余行应保存在数组中。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char fname[50] = "fiile.csv",toFind[50],str[200];
FILE * fp1 = fopen(fname,"r+");
char * line1 = NULL;
char array[2][200];
printf("Enter your id card number: ");
scanf("%s",toFind);
int count = 0;
while(fgets(str,200,fp1)){
line1 = strtok(str,"\n");
if(line1){
count++;
if(count == 1 && strstr(line1,toFind)){
strcpy(array[0],line1);
printf("Here is line %d: %s\n",count,array[0]);
}
else if(count == 2 && strstr(line1,toFind)){
strcpy(array[1],line1);
printf("Here is line %d: %s\n",array[1]);
}
}
}
return 0;
}
解决方法
用需要存储的元素声明数组(如果不知道最大值,则需要对malloc()
和realloc()
使用动态分配,但是我不会在这个答案中显示出来。
然后使用索引变量来保存要保存到的当前位置,跳过行时不会增加该位置。复制时使用此索引变量,而不是对每个索引进行硬编码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINES 1000
int main(){
char fname[50] = "file.csv",toFind[50],str[200],array[MAXLINES][200];
FILE * fp1 = fopen(fname,"r+");
char * line1 = NULL;
printf("Enter your id card number: ");
scanf("%s",toFind);
int index = 0;
while(index < MAXLINES && fgets(str,200,fp1)){
line1 = strtok(str,"\n");
if(line1)
{
if (!strstr(line1,toFind)) {
strcpy(array[index],line1);
printf("Here is line %d: %s\n",index,line1);
index++;
}
}
}
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。