来自以下格式的文本文件:
Name Surname ID Address
Name Surname ID Address
Name Surname ID Address
我需要提取每一个并将其放在一个变量中。
我尝试了以下两种方法:
while(fscanf(fp, "%s,%s,%d,%s\n", name2,surname2,&id2,address2) != EOF){
printf("Name: %s, Surname: %s, ID: %d, Address: %s\n",
&name2, &surname2, &id2, &address2);
}
这给了我错误的结果,它只为每一行读取一个单词,所以结果是这样的:
Name: Name Surname:@,a ID:2272012 Address: ?" Name: Surname Surname:@,a ID:2272012 Address: ?" Name: ID Surname:@,a ID:2272012 Address: ?" Name: Address Surname:@,a ID:2272012 Address: ?"
我使用的另一种方法是:
while(fscanf(fp, "%s,%s,%d,%s\n", name2,surname2,&id2,address2) == 4){
printf("Name: %s, Surname: %s, ID: %d, Address: %s\n",
&name2, &surname2, &id2, &address2);
}
什么都没读,没有任何反应。
我正在读取的文件是.dat,它用于分配,因此只能使用.dat。
答案 0 :(得分:2)
%s
将停止,因此无效。fgets()
读取整行通常会更好,然后担心解析它。答案 1 :(得分:2)
您声明您的文本文件格式为:
string<space>string<space>numeric<space>string<newline>
如果这是准确的,您的格式字符串必须完全匹配:
strings
| | numeric
| | | +-----string
| | | | +---newline
V V V V V
"%s %s %d %s\n"
^ ^ ^
| | |
spaces
这个assums每个string
字段是一个ASCII值块,没有空格/制表符等。你的代码缺少变量的定义方式,大概是这样的:
char name2[100] = {0};
char surname2[100] = {0};
int id2 = 0;
char address2[100] = {0};
在这种情况下,&
字符串中的名称前面不需要fscanf
。所以给定一个输入文件:
firt ast 1234 somebody@something.com
sec但是22352 goo@gle.com
thir haha 9999 nice@lly.com
以上变量声明,以下代码:
FILE * fp;
fp = fopen("test.txt", "r");
while(fscanf(fp, "%s %s %d %s\n", name2, surname2, &id2, address2) == 4)
printf("name: %s %s, id: %d, address %s\n", name2, surname2, id2, address2);
fclose(fp);
正确读取/显示值。
答案 2 :(得分:1)
首先,从&
printf
printf("Name: %s, Surname: %s, ID: %d, Address: %s\n",
name2, surname2, id2, address2);
如果输入txt文件中的字段之间的separoter是逗号,
Name,Surname , ID ,Address
Name ,Surname,ID,Address
Name,Surname,ID,Address
然后在fscanf
while(fscanf(fp, " %[^, ] , %[^, ] , %d , %[^\n]", name2,surname2,&id2,address2) != EOF){
printf("Name: %s, Surname: %s, ID: %d, Address: %s\n",
name2, surname2, id2, address2);
}
如果输入txt文件中的字段之间的separoter是空格
Name Surname ID Address
Name Surname ID Address
Name Surname ID Address
然后在fscanf
while(fscanf(fp, " %s %s %d %[^\n]", name2,surname2,&id2,address2) != EOF){
printf("Name: %s, Surname: %s, ID: %d, Address: %s\n",
name2, surname2, id2, address2);
}
答案 3 :(得分:0)
while(fscanf(fp, "%s,%s,%d,%s\n", name2,surname2,&id2,address2) != EOF){
printf("Name: %s, Surname: %s, ID: %d, Address: %s\n",
&name2, &surname2, &id2, &address2);
}
我认为这就是错误所在:
它应该是:
while(fscanf(fp, "%s,%s,%d,%s\n", name2,surname2,&id2,address2) != EOF){
printf("Name: %s, Surname: %s, ID: %d, Address: %s\n",
name2, surname2, id2, address2);
}