我的作业遇到了问题。我需要将文本文件中的一些数据扫描到结构中。 文本文件如下所示。
012345678;danny;cohen;22;M;danny1993;123;1,2,4,8;Nice person
223325222;or;dan;25;M;ordan10;1234;3,5,6,7;Singer and dancer
203484758;shani;israel;25;F;shaninush;12345;4,5,6,7;Happy and cool girl
349950234;nadav;cohen;50;M;nd50;nadav;3,6,7,8;Engineer very smart
345656974;oshrit;hasson;30;F;osh321;111;3,4,5,7;Layer and a painter
每一项数据与其匹配的变量。 ID = 012345678 名字 = 丹尼 等等……
现在我不能使用 fscanf,因为没有间距,而且 fgets 会扫描所有行。
我用 %[^;]s 找到了一些解决方案,但是我需要编写一个代码块,然后为每项数据复制并粘贴 9 次。
在不更改文本文件的情况下是否还有其他选项,类似于我用 fscanf 编写的代码,如果每个数据项之间有间距?
*************** 更新 **************
您好,首先,非常感谢大家的帮助。 我不明白你所有的答案,但这里我确实使用了一些东西。
这是我的代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char *idP, *firstNameP, *lastNameP;
int age;
char gender, *userNameP, *passwordP, hobbies, *descriptionP;
}user;
void main() {
FILE *fileP;
user temp;
char test[99];
temp.idP = (char *)malloc(99);
temp.firstNameP = (char *)malloc(99);
temp.lastNameP = (char *)malloc(99);
temp.age = (int )malloc(4);
temp.gender = (char )malloc(sizeof(char));
temp.userNameP = (char *)malloc(99);
fileP = fopen("input.txt", "r");
fscanf(fileP, "%9[^;];%99[^;];%99[^;];%d;%c", temp.idP,temp.firstNameP,temp.lastNameP,&temp.age, temp.gender);
printf("%s\n%s\n%s\n%d\n%c", temp.idP, temp.firstNameP, temp.lastNameP, temp.age, temp.gender);
fgets(test, 60, fileP); // Just testing where it stop scanning
printf("\n\n%s", test);
fclose(fileP);
getchar();
}
一切正常,直到我扫描 int 变量,之后它不扫描任何东西,我得到一个错误。
非常感谢。
最佳答案
如评论中所述,fscanf
可能是最短的选项(尽管 fgets
后跟 strtok
,手动解析是可行的选项) .
您需要为字符串字段使用 %[^;]
说明符(意思是:字符串不同于 ;
) ,字段由 ;
分隔以使用实际的分号(我们特别要求不要将其作为字符串字段的一部分使用)。最后一个字段应该是 %[^\n]
以消耗到换行符,因为输入没有终止分号。
您还应该(始终)将使用 scanf
系列函数读取的每个字符串字段的长度限制为比可用空间少一个(终止 NUL 字节是 +1)。因此,例如,如果第一个字段的长度最多为 9 个字符,则您需要 char field1[10]
并且格式为 %9[^;]
。
在格式字符串的开头放置一个空格通常是个好主意,以消耗任何空格(例如前面的换行符)。
当然,您应该检查 fscanf
的返回值,例如,如果按照示例有 9 个字段,则它应该返回 9
。
所以,最终的结果应该是这样的:
if (fscanf(file, " %9[^;];%99[^;];%99[^;];%d;%c;%99[^;];%d;%99[^;];%99[^\n]",
s.field1, s.field2, s.field3, &s.field4, …, s.field9) != 9) {
// error
break;
}
(或者,用逗号分隔数字的字段可以读作四个单独的字段,如 %d,%d,%d,%d
,在这种情况下,计数将达到 12 .)
关于c - 从文本文件中扫描数据,每个数据项之间没有间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53937287/