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

Re: Determining the number of unique words in a .txt file

 
0
  #7
Dec 3rd, 2008
The maximum length of a word is 20, so the character array needs to be 21. The maximum numbers of words is 100, if there are more than 100 words I need to return a message saying something like "The stats did not use the words after the 100th word"

Anyways, I'm having a hard time even starting the program. I'm starting off by trying to read and store the words of the text file. My text book has code for reading line by line a text file and then displaying it. So I figured I should start with that. Heres the code-

  1. #include <iostream>
  2. #include <fstream>
  3. #include <cstdlib> // needed for exit()
  4. #include <string>
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. string filename = "text.dat"; // put the filename up front
  10. string line;
  11. ifstream inFile;
  12.  
  13. inFile.open(filename.c_str());
  14.  
  15. if (inFile.fail()) // check for successful open
  16. {
  17. cout << "\nThe file was not successfully opened"
  18. << "\n Please check that the file currently exists."
  19. << endl;
  20. exit(1);
  21. }
  22.  
  23. // read and display the file's contents
  24. while (getline(inFile,line))
  25. cout << line << endl;
  26.  
  27. inFile.close();
  28.  
  29. cin.ignore(); // this line is optional
  30.  
  31. return 0;
  32. }

Heres my code split into two functions, however it does not compile. I get an error at the while statement.-
  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. char filename[fileSize];
  16.  
  17. cout << "Please enter the name of the file you wish to open: "<< endl;
  18. cin.getline(filename,fileSize);
  19.  
  20. displayFile (filename);
  21. cin.ignore();
  22. }
  23.  
  24. void displayFile (char fileName[] )
  25. {
  26. ifstream inFile;
  27.  
  28. char line [101];
  29.  
  30. inFile.open(fileName);
  31.  
  32. while (getline(inFile, line))
  33. cout << line << endl;
  34.  
  35. inFile.close();
  36.  
  37. return 0;
  38. }
My code is nearly identical except for the fact that I use character arrays instead of strings, so I'm not sure why its not compiling.
Also, is this a good way to start off the program? Or should I try something else.
Reply With Quote