View Single Post
Join Date: Nov 2008
Posts: 13
Reputation: matt_570 is an unknown quantity at this point 
Solved Threads: 0
matt_570 matt_570 is offline Offline
Newbie Poster

Determining the number of unique words in a .txt file

 
0
  #1
Dec 2nd, 2008
Hey I have to write a program that reads a text file that contains a list of words, 1 word per line. I have to store the unique words and count the occurrences of each unique word. When the file is completely read, I have to print the words and the number of occurrences to a text file. The output should be the words in alphabetical order along with the number of times they occur. Then print to the file some statistics:

I have to use character arrays instead of strings.
I must use the linear search (something that looks like this)
  1. array.int search ( int array[], int number, int key )
  2. {
  3. int pos = 0;
  4.  
  5. while(pos < number && array[pos] != key)
  6. pos++;
  7.  
  8. if( pos == number)
  9. pos = 0;
  10. else
  11. pos = 1;
  12.  
  13. return pos;
  14. }
to determine if a word is in the array. The array is an array of structures and that the key is a char array so the string comparison must be used. The search task should be a separate function.
The search must be a separate function that returns an integer values. I cant use a for loop and the function must have only one return statement.
I tried to start off by reading the files and storing the words
  1. #include <iostream>
  2. #include <fstream>
  3. #include <cstdlib>
  4. #include <string>
  5. #include <iomanip>
  6. using namespace std;
  7.  
  8. void displayFile( char []);
  9.  
  10. void main ()
  11. {
  12. int const wordLength = 21;
  13. int const Num = 101;
  14. int const fileSize = 255;
  15.  
  16.  
  17. char filename[fileSize];
  18. ifstream inFile;
  19.  
  20.  
  21. struct
  22. {
  23. char word[wordLength];
  24. int count;
  25. } wordCount;
  26.  
  27. wordCount array[Num];
  28.  
  29. cout << "Please enter the name of thr file you wish to open: "<< endl;
  30. cin >> filename;
  31.  
  32. displayFile (filename);
  33.  
  34. }
  35.  
  36. void displayFile (char fileName [] )
  37. {
  38. ifstream infile;
  39. char array [101];
  40. char line [101];
  41. int ch;
  42. int i;
  43. infile.open (fileName);
  44.  
  45. while ((ch = infile.peek()) != EOF)
  46. {
  47. infile.getline (line, 101);
  48. line = array[i];
  49. i++;
  50. }
  51.  
  52. for (int j = 0; j<101; j++)
  53. cout << array[j] << endl;
  54. infile.close ();

Any tips would be appreciated, and thanks in advance.
Reply With Quote