I am new to C and this is a small part of my homework assignment. I have to read in a file consisting of students names and scores. I have to separate the names from the scores. I used 2 2d char arrays to do so. My professor told us to use fgetc to read in the characters. After I read the file I have to sort the scores along with the corresponding name in ascending order(I have not implemented my sort yet so I am not asking for help with that yet). My problem is when I output the arrays it spits out garbage along with some of the correct info. The assignment has more to it but I am trying to fix problems on a small scale first before I try the full assignment.
This is a sample text file.
jim 97
jake 51
bill 84
ray 77
This is the garbage output I get:
jim 97���
ke ���84@>�77
4@>�77
l �77
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
int ch;
char name[10][5];
char score[5][5];
FILE *fp;
fp = fopen("infile.txt", "r");
int y = 0;
int x = 0;
int line = 0;
while((ch=fgetc(fp))!=EOF)
{
if(ch != '\n')
{
if(isalpha(ch))
{
name[line][x] = ch;
x++;
}
else if(isdigit(ch))
{
score[line][y] = ch;
y++;
}
}
else if(ch == '\n')
{
line++;
}
}
int i = 0;
for ( i = 0 ; i < 5 ; i++ )
{
printf("%s", name[i]);;
printf(" ");
printf("%s\n", score[i] );
}
printf(" ");
return 0;
}