I can't find a way to solve this one.
I have a text file like this : score.txt
pat 20
ananna 20
radis 19
The number of lines can be between 10 and anything.
My goal is to print the 10 line where the integers are the higher, in order.
I tried with this, but I can't even read the number in my text file.
void fillScore(){
FILE* f =NULL;
f= fopen("score.txt", "r");
char name[20];
int score,i,j,tmp;
int tabScore[10]={-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
char tabName[10][20];
if (f==NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
while(fscanf(f,"%s%d",name,&score)==1){
printf("TEST : %d - ",score);
for(i=0;i<10;i ){
if(score>tabScore[i]){
tmp=tabScore[i];
tabScore[i]=score;
for(j=i 1;j<10;j ){
score=tabScore[j];
tabScore[j]=tmp;
tmp=score;
}
}
}
}
for(i=0;i<10;i ){
printf("%d\n",tabScore[i]);
}
fclose(f);
}
Does anybody have a hint on this ? I can get how to do it. I know it's not a great question, because it shows a lack of research, but I swear that I search on the web for hours.
Thanks a lot.
CodePudding user response:
You're testing fscanf
against the wrong value 1
.
As per man page,
on success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure
Since you're asking *scanf()
to convert two items, you want to check its return value against 2
.
The following works:
...
while(fscanf(f,"%s%d",name,&score) == 2){
...