如何从csv文件中获取特定的行? [英] how to get specific rows from csv file?
问题描述
我已经编写了一个代码,其中我试图获取从"A" 开始的所有行.我的csv文件中有A,A12等,我想读取所有这些行.但是我得到了以下错误.不知道我哪里做错了.请帮助.
I've written a code, wherein i'm trying to get all the rows which start from "A". I have A, A12 etc in my csv file and i want to read all those rows. But i got the following error. Not sure where i went wrong. Kindly help.
CSV文件
M,2,lion
A,1,tiger
B,2,cat
A1,7,dog
C,3,man
A2,9,mouse
A23,9,pouch
myfile.c
#include <stdio.h>
#include <stdlib.h>
#define NUMLETTERS 100
typedef struct {
char letter[100];
int number;
char ani[100];
} record_t;
int main(void) {
FILE *fp;
record_t records[NUMLETTERS];
size_t count = 0;
fp = fopen("letters.csv", "r");
if (fp == NULL) {
fprintf(stderr, "Error reading file\n");
return 1;
}
while (fscanf(fp, " %s,%d,%s", records[count].letter, &records[count].number, records[count].ani) == 3) {
count++;
}
for (size_t i = 0; i < count; i++) {
if(records[i].letter== "A"){
printf("%s,%d,%s\n", records[i].letter, records[i].number,records[i].number);
}
}
fclose(fp);
return 0;
}
错误
myfile.c:29:16: warning: format ‘%s’ expects argument of type ‘char *’, but argument 4 has type ‘int’ [-Wformat=]
printf("%s,%d,%s\n", records[i].letter, records[i].number,records[i].number);
推荐答案
由于您搜索以A
开头的字段,因此只需要比较letter
的第一个字母,因此第28行变为:
Since you search fields that start with A
, you only need to compare the first letter of letter
, so your line 28 becomes:
if(records[i].letter[0] == 'A'){
编译器告诉您,您尝试将整数显示为字符串,这是因为在第29行中有一个错字:number
而不是ani
,该行应为:
And your compiler told you that you try to display an integer as a string, it's because you have a typo in line 29: number
instead of ani
, the line should be:
printf("%s,%d,%s\n", records[i].letter, records[i].number,records[i].ani);
对不起,我得到了我的输出,但是在输出中添加了一些额外的列,分别为"0" A,1,tiger,0,A1,7,dog,0,A2,9,mouse,0,A23,9,pouch, 0,– Abhik 2小时前
Sorry i got my output but some extra column added in my output as "0" A,1,tiger,0, A1,7,dog,0, A2,9,mouse,0, A23,9,pouch,0, – Abhik 2 hours ago
它来自您的scanf
调用:在scanf
中,%s
将读取直到找到一个空格(空格,制表符或换行符).找到第一个逗号后,您必须告诉scanf停止读取letter
.为此,将%s
替换为%99[^,]
.此处提供更多说明: Scanf指南.
It comes from your scanf
call: in scanf
, %s
will read until in find a space (space or tab or line feed). You have to tell to scanf to stop too read letter
after the first comma found. To do this, replace %s
with %99[^,]
. More explanations here: Scanf guide.
因此您的阅读循环应如下所示:
So your reading loop should looks like:
while (fscanf(fp, " %99[^,],%d,%s", records[count].letter, &records[count].number, records[count].ani) == 3) {
count++;
}
这篇关于如何从csv文件中获取特定的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!