1. /* Program creates a user-named .txt file (if file does not exist)
  2. in which user can build a list of words up to user-chosen
  3. number of entries desired. Console then displays all entries in
  4. .txt If same file is reopened, the list is appended from the end. */
  5.  
  6. #include <iostream>
  7. #include <string>
  8. #include <fstream>
  9.  
  10. using namespace std;
  11.  
  12. int main()
  13. {
  14.  
  15. string filename; // creates string for user input
  16. cout << "Input file name to open: ";
  17. cin >> filename;
  18. cout << endl;
  19.  
  20. fstream myfile(filename.c_str(), ios::out | ios::app); // declares fstream class "myfile". Opens file from user input.
  21. if (myfile.is_open())
  22. {
  23. int x = 0;
  24. cout << "Enter the number of words you would like to enter: ";
  25. cin >> x;
  26. cout << endl;
  27.  
  28. string input; // User controlled for-loop from x
  29. for (int i = 0;i < x; i++)
  30. {
  31. cout << "Enter word " << i <<":";
  32. cin >> input;
  33. myfile << input << endl;
  34. }
  35. cout << endl;
  36. myfile.close();
  37. }
  38. else
  39. cout << "Unable to open file!" << endl;
  40. //-------------------------------------------------------------------------------------------------------
  41. string line; // creates string to read line from .txt
  42.  
  43. myfile.open("example.txt", ios::in); // Opens created file (myfile declared on line 14)
  44. if (myfile.is_open())
  45. {
  46. int numPlace = 1;
  47. cout << "The list is:" << endl;
  48.  
  49. while (!myfile.eof()) // while-loop to print what is in .txt aka(myfile.good())
  50. {
  51. getline (myfile, line);
  52. cout << numPlace << ". "
  53. << line << endl;
  54. numPlace++;
  55. }
  56. myfile.close();
  57. }
  58. else
  59. cout << "Unable to open file!" << endl;
  60.  
  61. return 0;
  62. }