My line count in the text file is 8 but somewhere my program is reading outside the array for both username and score. Im getting the huge spazzy errors with the weird characters. Any help?
Code:
void high_scores()
{
FILE *my_file1, *my_file2, *my_file3, *my_file4;
int i = 0, scorearray[20], temp_scores, x=0, linecount, charcount, wordcount, flag = 1, counter =0;
char usernamearray[20][20], temp_names[20], ch;
my_file3 = fopen("username1.txt", "r");
my_file4 = fopen("username2.txt", "r");
// Initialize counter variables
linecount = 0;
charcount = 0;
wordcount = 0;
system("mode con: cols=60 lines=80");
// If file opened successfully, then write the string to file
if (my_file3)
{
//Repeat until End Of File character is reached.
while ((ch=getc(my_file3)) != EOF) {
// Increment character count if NOT new line or space
if (ch != ' ' && ch != '\n') { ++charcount; }
// Increment line count if new line character
if (ch == '\n') { ++linecount; }
if (ch == ' '|| ch == '\n') {++wordcount;}
}
if (charcount > 0) {
++linecount;
++wordcount;
}
}
else
{
printf("Failed to open the file\n");
}
printf("%d", linecount);
counter = linecount/2;
getch();
for(i = 0; i <= counter; i++)
{
fscanf(my_file3, "%s\n", usernamearray[i]);
fscanf(my_file3, "%d\n", &scorearray[i]);
}
//Initalized the sorting process
while (flag==1)
{
flag=0;
for (i=1; i == counter ; i++)
{
if (scorearray[i]>scorearray[i+1])
{
flag=1;
temp_scores=scorearray[i];
scorearray[i]=scorearray[i+1];
scorearray[i+1]=temp_scores;
strcpy(temp_names, usernamearray[i]);
strcpy(usernamearray[i], usernamearray[i+1]);
strcpy(usernamearray[i+1], temp_names);
flag = 1;
}
}
system("cls");
}
fclose(my_file3);
my_file3 = fopen("username1.txt", "a");
system("pause");
fflush(stdin);
for(i=1; i<=counter; i++)
{
printf("\t%s - %d\n\n", usernamearray[i], scorearray[i]);
}
system("pause");
}