简体   繁体   English

如何在 C 中正确 fscanf txt 文件

[英]How to properly fscanf txt file in C

For example: #1 Tutti/Leeloo/853811356;例如:#1 Tutti/Leeloo/853811356; N N

And this is my code:这是我的代码:

typedef struct{
    int redni;
    char prezime[50+1];
    char ime[50+1];
    char osobna[50+1];
    char glasao[10];

} Biraliste;


int nBiraci=0;

while(fscanf(biralisteTxt,  "%d %[^/]/%[^/]/%[^;];%[^\n]",
             biraci[n].redni, biraci[n].prezime, biraci[n].ime, biraci[n].osobna, biraci[n].glasao  ) == 5)
{
    nBiraci++;

}

for(i=0;i<nBiraci;i++)
{

        fprintf(statistikaTxt, "%d %s %s %s %s", 
&biraci[i].redni, biraci[i].prezime, biraci[i].ime, biraci[i].osobna, biraci[i].glasao );


}

Can someone help mi with right fscanf and fprintf, and is it ok to fscanf redni with %d or it should be %s.有人可以用正确的 fscanf 和 fprintf 帮助 mi,用 %d 来 fscanf redni 是否可以,或者应该是 %s。

" #%d %[^/]/%[^/]/%[^;];%[^\\n]" - 这是正确答案,谢谢

The following code fixes two problems.下面的代码解决了两个问题。

  • scanf must get the address of the variable to fill, this &biraci... scanf 必须得到要填充的变量的地址,这个&biraci...
  • the index must be nBiraci and not n , thus &biraci[nBiraci]...索引必须是nBiraci而不是n ,因此&biraci[nBiraci]...
  • there must be a # in front of %d %d 前面必须有一个#
int nBiraci=0;
while(fscanf(biralisteTxt,  " #%d %[^/]/%[^/]/%[^;];%[^\n]",
             &biraci[nBiraci].redni, (char*)&biraci[nBiraci].prezime,
             (char*)&biraci[nBiraci].ime, (char*)&biraci[nBiraci].osobna,
             (char*)&biraci[nBiraci].glasao) == 5)
{
    nBiraci++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM