Trouble with string output...Help!
I need help with trying to determine why my array is being overwritten. The problem is that when I run this code and then print out the results, array Var[m] gets filled from beginning to end with the last value that sscanf got from the data file "Data.txt". If you look at the code the sscanf puts the last field of data into a variable called t5. Therefore I only see "S2_536" from the data file in all 15 array elements. When I ran the code through the debugger I saw the first element get the correct value ("S2_632" from the data file), then the second time through the loop the first and second elements both had the second elements value (or "S2_627" from the data file)... and so on until all 15 elements contained the last or 15th elements value. Each element for Var[m] should have it's respective data from line one through line 15. All other arrays that I print out look good except this one. Why is it doing this? What am I doing wrong? Please run this code below to see exactly what I'm saying. Thanks for your help!
#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXCHARS 80
int m;
FILE *infp;
char line1[MAXCHARS];
char t1[20], t2[20], t3[20], t4[20], t5[20];
int int Index[25], Pos[25][11], int Var[25];
int main()
{
fp = fopen("Data.txt", "r");
if(fp == NULL) {
fprintf(stderr, "can't open %s\n", "Data.txt");
exit(EXIT_FAILURE);
}
for (m=0; m<15; m++) {
if(fgets(line1, MAXCHARS, infp) != NULL) {
sscanf (line1, "%s %s %s %s %s", t1, t2, t3, t4, t5);
Index[m] = atoi(t1);
Pos[m][1] = atoi(t2);
Pos[m][2] = atoi(t3);
Pos[m][3] = atoi(t4);
Var[m] = t5;
}
}
for (m=0; m<15; m++) {
printf("Index = %i\n",Index);
printf("Index = %i\n",Pos[m][1]);
printf("Index = %i\n",Pos[m][2]);
printf("Index = %i\n",Pos[m][3]);
printf("Index = %s\n",Var[m]);
}
// Done reading input file at this point
fclose(infp);
return(0);
}
Data.txt is a text file, 15 lines long, each field separated by a space and looks exactly like this:
1 0 0 1 S2_632
2 21 21 2 S2_627
3 30 51 2 S2_621
4 18 69 0 S2_613
5 18 87 0 S2_606
6 19 106 0 S2_599
7 57 163 1 S2_595
8 14 177 0 S2_589
9 18 195 0 S2_587
10 15 210 0 S2_579
11 14 224 0 S2_572
12 21 245 0 S2_566
13 21 266 0 S2_554
14 14 280 0 S2_542
15 13 293 0 S2_536