I am trying to write a program that reads lines from a .txt and inputs them to 2 different arrays.
So far I have this:
#include <stdio.h>
int main() {
FILE * ifp = fopen("input.txt","r");
FILE * ofp = fopen ("output.txt", "w");
int participants = 0, i;
char name [10];
float grade [10];
float perc [10];
fscanf(ifp, "%d", &participants);
for (i=1; i<participants; i++) {
fscanf(ifp, "%s", &name);
fscanf(ifp, "%f", &grade);
}
printf( "%d\n", participants);
printf( "%s\n", name);
printf( "%f\n", grade);
fclose(ifp);
fclose(ofp);
return 0;
}
The txt I'm trying to read is:
2
Optimus
45 90
30 60
25 30
50 70
Megatron
5 6
7 9
3 4
8 10
My problem is that it picks up the first 2 lines but stops when it gets to the numbers. I'm trying to get the names into an array and all the numbers, in pairs in a different array. Right now I'm just trying to check to see if I am picking up the numbers in the array but its not picking them all up.
This is the output that I get:
2
Optimus
0.000000
Any ideas?
EDIT
This is my new code after some changes:
#include <stdio.h>
int main() {
FILE * ifp = fopen("input.txt","r");
FILE * ofp = fopen ("output.txt", "w");
int participants = 0, i , j;
char name [10];
int grade [26];
float perc [26];
fscanf(ifp, "%d", &participants);
for (i=1; i<participants; i++) {
fscanf(ifp, " %s", name);
fscanf(ifp, " %d", grade);
}
printf( "%d\n", participants);
printf( "%s\n", name);
printf( "%d\n", grade[0]);
fclose(ifp);
fclose(ofp);
return 0;
}
And my new output is :
2
Optimus
45
EDIT 2
What I need to do with those numbers later is divide the first number in a line with the second number in that same line, multiply it by 10, and then have it display "*" according to the number. So it would print out like this:
Optimus
+: *****
-: *****
*: ********
/: *******
Megatron
+: ********
-: *******
*: *******
/: ********
"+" is the first line under a name. "-" is the second line under that same name. "*" for the third. "/" for the fourth.