Reading a file, sorting and counting contents, help?
Ok I have program due for my class. And it's a doozy, at least for me, I'm supposed to give the user a choice of 5 files to read. Then tell them the first and last 10 words of the file and how many times that word occurs in the file. Then sort the words alphabetically and tell them the first and last 10 words again and how many times they occur. I need some help with a few aspects
1. How do I print the last 10 words?
2. How can I get the count to print in a table form. All pretty and even and stuff.
3. For some reason it only works when the user chooses 1. I have all the files saved in the same place. I can't see why it wouldn't work for the other choices.
Here's what I have so far, and just ignore that the count is 0 for every word, I haven't worked on that part yet. Thanks for any help in advance.
Code:
#include <stdio.h>
#include <string.h>
int main( )
{
FILE *myfile = NULL; //file pointer
int fileselect; //holds the choice
char filename[30]; //holds the file name
char words[5000][20]; //array to hold the words
int i; //for the loop
int x=0;
while(1)
{
printf( "\nSelect the number of the text file to read\n");
printf( "1 - words_emancip\n");
printf( "2 - words_flatland\n");
printf( "3 - words_macbeth\n");
printf( "4 - words_prince\n");
printf( "5 - words_purloin\n");
printf("6 - Quit\n");
fflush( stdin);
scanf( "%d", &fileselect);
printf( "\n");
switch(fileselect)
{
case 1: strcpy(filename, "words_emancip.txt");
break;
case 2: strcpy(filename, "words_flatland.txt");
break;
case 3: strcpy(filename, "words_macbeth.txt");
break;
case 4: strcpy(filename, "words_prince.txt");
break;
case 5: strcpy(filename, "words_purloin.txt");
break;
case 6: printf("Goodbye!\n");
return 0;
break;
default: printf("That is not a valid choice.\n");
break;
}
myfile=fopen(filename, "r");
if(myfile==NULL)
{
printf("File not found\n");
}
//stores the words into the array words
for(i=0; !feof(myfile); i++)
{
fscanf(myfile, "%s ", &words[i]);
}
//print the first 10
printf( "First 10 words of the unsorted array\n");
for(i=0; i<10; i++)
{
printf("Word # %d = %s ,Count = %d\n", i, words[i], x);
}
fclose(myfile);
}
return 0;
}