![](/img/trans.png)
[英]How to use fscanf and fgets from a text file with ints and strings?
[英]How to properly use fscanf and fgets to read from file
我是C语言(这是我的第一语言)编程的新手,我的英语不太好,因此对不起语法...顺便说一句,我想知道您是否可以帮助我:从文件中读取数组的组件,将其设置为数组的一部分,并在屏幕中将其视为输出。 我使用以下信息创建了一个文件:
Rossi,Mario,M,mariorossi @ gmail.com,3923333332,Portiere Bianchi,Giuseppe,M,giuseppebianchi @ gmail.com,3470000021,Attaccante Ferrari,Anna,F,annaferrari @ gmail.com,3466482645,Attaccante Romano,Antonio,M ,antonioromano @ gmail.com,3450394672,Centrocampista
并尝试编码,我最终得到了这个:
#include <stdio.h>
#include <stdlib.h>
struct dati_giocatori {
char cognome[20];
char nome[20];
char genere[20];
char email[20];
int telefono;
char ruolo[20];
};
typedef struct dati_giocatori GIOCATORE;
void lettura(FILE *file, GIOCATORE *vettore, int dim);
void stampa(GIOCATORE *vettore, int dim);
int main (){
FILE *file;
GIOCATORE *vettore;
int dim;
vettore=(GIOCATORE*)malloc(dim*sizeof(GIOCATORE));
printf("how many players do you want to see?");
scanf("%d",&dim);
file=fopen("Giocatori.txt","r");
lettura(file,vettore,dim);
stampa(vettore,dim);
system("pause");
return 0;
}
void lettura(FILE *file, GIOCATORE *vettore, int dim){
int i=0;
if(file){
while(!feof(file) && i<dim){
fscanf(file,"%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],[^\n]", vettore[i].cognome,vettore[i].nome,vettore[i].genere,vettore[i].email,&vettore[i].telefono,vettore[i].ruolo);
i++;
}
}
else{
printf("Error.");
}
}
void stampa(GIOCATORE *vettore, int dim){
int i=0;
while(i<dim){
printf("%s,%s,%s,%s,%d,%s\n", vettore[i].cognome,vettore[i].nome,vettore[i].genere,vettore[i].email,vettore[i].telefono,vettore[i].ruolo);
i++;
}
}
但是效果不是很好。 我知道我的fscanf有一些问题(可能),我想知道malloc的使用是否正确...您能帮我吗? 我在哪里犯了错误? 我该如何解决? 代码应如何使用fgets而不是fscanf? 我是否以正确的方式使用分隔符?
好的,非常感谢您的答复,我将用一个长变量处理10位数字的电话号码,但是我仍然不知道如何正确使用fscanf。 这是第一次使用分隔符,这使我感到困惑。 我的格式说明符是“%s,%s,%s,%s,%ld,%s”,对吗? 但是我应该如何将它们放在fscanf中呢? 在fscanf中的参数“ file”之后我该写些什么?
fscanf(file,"%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],[^\n]",...
您的格式说明符不正确; 如果您告诉fscanf
要读取的数据是用逗号分隔的,并且用方括号外的逗号进行处理,则无需指定要放入的内容( [^,]
),并且缺少格式说明符。 尝试为fscanf
提供与stampa
函数中给printf
相同的格式。 注意:整数变量不能正确容纳10位电话号码,请使用long
变量或将其视为字符串。
另一方面, fgets
会将整行读入字符串缓冲区,因为它不接受格式说明符,因此最终只能得到一个包含整个行的字符串,然后应使用sscanf
这样的内容解析它使用fscanf
方式相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.