Hi, I'm relatively new to programming, so let me know if I don't make sense and I'll elaborate.
I've pasted my main function below. Its supposed to take in a data file and count the frequency of each word, then print all the information out in another data file. (so a sample output would be:
Hello, 2
John, 4
I, 3 etc.
Now the strange thing is, the program ONLY works (the output is generated by the fprintf function subsequent to the return) IF I include the printf function in the while loop (in bold).
Why should this affect the operation of the program... I mean all it does is just print out a line.
Any advice is greatly appreciated. My hair's turned grey.
PS I've attached the code, so you can try compiling it to see what I mean. The input file is called doc.txt... so just get a paragraph, not too long mind, and test it. The output is freq.txt. I've included as many comments as I could to make the program more readable, but its still relatively messy. Sorry if that causes trouble.
Code:
int main (void)
{
FILE *infile, *outfile;
char line[100];
struct WORD w[500]; //assuming that there are no more than 500 different words. structure contains an int freq, and char word[30]
extern int counter; // counts the number of words (done in different function
int k=0;
infile = fopen ("doc.txt", "r");
outfile = fopen ("freq.txt", "w");
while(fscanf(infile, "%c", &line[0]) == 1)
{
k=1;
do{
fscanf (infile, "%c", &line[k]);
k++;
} while (line[k-1] != '\n');
line[k-1] = '\0';
// printf("%s\n", line); /* fprintf function (below) only works */
/* if this printf function is inserted */
process (line, w); /* each line is taken in and processed. New words are added into w; and existing words increases frequency of the concerned element */
}
for (k=0; k<counter; k++)
fprintf(outfile, "%s %i\n", w[k].word, w[k].freq); /* This is the desired output... */
return 0;
}