-
Noob file i/o problem
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;
}
-
%s reads until it reaches a null character. I think you want to manually enter one in at the end of the array.
-
I suggest you use fgets to read line by line of the file and then process it. You read 1st line, you process it, you read 2nd line, you process it and so on.
One example, from my first professor of programming that made me understand how things are played, can be found at this example. It copies the data of a file to another file.
-
Thanks for the help camel-man and std10093. I think I am on the right track now. I am going to use fgets. Ill post again if I have more questions.