gpt4 book ai didi

c - 如何让 fscanf 从 .csv 文件中读取,将逗号之间和每行上的每个部分读取到字符串中?

转载 作者:行者123 更新时间:2023-11-30 14:39:22 26 4
gpt4 key购买 nike

我正在编写一个程序来从 .csv 文件读取 map ,我想读取文件的每个部分,然后将其中的信息写入二维数组中的相关结构中。我使用 fscanf 获取行数和列数来 malloc 结构数组,并且我可以读取第一个值,直到逗号并处理它。但是,也可能存在空白字段,出现在一行中,例如 1 goat,,2 cat我的程序读取 1 和 goat 并处理它,但它扫描的下一个东西只是 cat。我希望它读取 2 个逗号,识别出其中没有任何内容,然后转到 cat 并读取该内容,然后再转到下一行

我不知道如何为 fscanf 执行正确的格式规范。目前我有 fscanf(fp, "%[^,]", Animal);

/*scans file until comma, writes the scanned text into array*/

fscanf(fp, "%[^,]", animal);
printf("Scanned in string for y (%d) and x %d = (%s)\n", j, k, anima;l);
if (strcmp(animal, "") != 0)
{
/*if first character is lowercase, change to upper)*/
if(animal[0]>90)
{
animal[0]=animal[0]-32;
}
/*Checks if item is cat goat or mouse by checking 1st letter of the scanned in array is C G or M*/
if(strncmp(animal,"C", 1) == 0)
{
/*copies name of the animal into the struct*/
strcpy(animalarray[j][k].name, "Cat");

/*write animal name into struct*/
token =strtok(animal, spaceDelimeter);
/* The 1 is already dealt with, can be moved past*/
token = strtok(NULL, commaDelimeter);
printf("token = %s\n", token);


animalarray[j][k].number= atoi(token);


printf("Animal is %s, number is %d\n", animalarray[j][k].name, animalarray[j][k].number);
}

输入文件是 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

2,31只山羊,2只猫3只老鼠,5只山羊,

我运行时的输出是

rows  2, columns  3 
Scanned in string for row 0 and column 0 = 1 goat
token = goat
Animal is goat, number is 1
Scanned in string for row 0 and column 1 = 2
token = (null)
Segmentation fault (core dumped)

应该是

...
Scanned in string for row 0 and column 1 = "blank"
Scanned in string for row 0 and column 1 = 2 cat
...

最佳答案

fscanf无法扫描空字符串,但您可以使用返回值来检测是否扫描过任何内容:

FILE *f = fopen(filename, "r");
char buf[80];
int row = 0;
int col = 0;

while (1) {
int n = fscanf(f, "%79[^,\n]", buf);

if (n == EOF) break;
if (n == 0) *buf = '\0';

printf("[%d, %d] '%s'\n", row, col, buf);

if (fgetc(f) == ',') {
col++;
} else {
col = 0;
row++;
}
}

如果什么也没做,n是 0 - 在这种情况下,代码通过在第一个字符中写入空终止符来显式清除输入字符串。通过读取逗号还是换行符来检测行和列。 (下一个字符只能是逗号、换行符或文件末尾。)

另一种可能性是使用 fgets 逐行读取输入然后扫描每一行。字符串扫描函数sscanf具有与 fscanf 相同的限制,因此最好使用字符串函数,例如 strchr 。这里我用了strcspn来自<string.h> ,它对字符串中的字符进行计数,直到找到任何给定字符或字符串末尾。这使得它与%[^n ...]非常相似。格式为fscanf :

FILE *f = fopen(filename, "r");
char line[80];
int row = 0;

while (fgets(line, sizeof(line), f)) {
int col = 0;
int offset = 0;

while (line[offset]) {
int next = strcspn(line + offset, ",\n");

printf("[%d, %d] '%.*s'\n", row, col, next, line + offset);
offset += next + 1;

col++;
}

row++;
}

同样,列和行检测是根据上下文进行的。

关于c - 如何让 fscanf 从 .csv 文件中读取,将逗号之间和每行上的每个部分读取到字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56107844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com