簡體   English   中英

使用fscanf()讀取多個值(如下面的文本文件中所示)

[英]reading using fscanf() for multiple values (as in the text file below)

fscanf()的新手... plz幫助

程序

#include<stdio.h>
typedef struct
{
int rollnum;
char name[30];
int mark1;
int mark2;
int mark3;
}data;

int main(int argc,char* argv[])
{
int total,c1,c2,i;
char str[30];
FILE *original,*pass,*fail;
data *student;

original=fopen("C:\\Users\\user\\Desktop\\struct.txt","r");
pass=fopen("C:\\Users\\user\\Desktop\\pass.txt","w");
fail=fopen("C:\\Users\\user\\Desktop\\fail.txt","w");

for(i=0;i<5;i++)
{
fscanf(original,"%d %s %d %d %d",
&(student+i)->rollnum,
(student+i)->name,
&(student+i)->mark1,
&(student+i)->mark2,
&(student+i)->mark3);
total=student[i].mark1+student[i].mark2+student[i].mark3;
if(total>50)
fprintf(pass,"%d. %s %d\n",c1,student[i].name,total);
else
fprintf(fail,"%d. %s %d\n",c2,student[i].name,total);
c1++,c2++;
}
printf("Successful\n");
fclose(original);
fclose(pass);
fclose(fail);
return 0;
}

**struct.txt**
1 blesswin 20 40 50
2 sam 40 10 20
3 john 50 20 60
4 james 50 40 70
5 peter 10 40 80

該程序是根據學生的總數將他們分為兩個文件...雖然fscanf函數似乎有些問題...我們的幫助表示贊賞...感謝提前

沒有任何錯誤,更難查明您在哪里出現問題,但可能與您沒有為學生分配內存這一事實有關:

data *students;

students = malloc(number_of_students * sizeof(*students));
if (students==NULL)
    printf("Error: failed to allocate memory\n");

將文件中的數據加載到分配的內存中看起來像

for(i=0;i<number_of_students ;i++) {
    fscanf(original,"%d", &(students[i].rollnum));
}

當您不再需要分配內存時,別忘了釋放它

free(students);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM