Advertisement
CH1156

Finds a word in a text document and replaces it.

Oct 22nd, 2012
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4. #include <sstream>
  5.  
  6. using namespace std;
  7.  
  8. int find(string& storeText, ifstream& fileIn);
  9. bool updateHistory(bool& r);
  10.  
  11. int main()
  12. {
  13.     string fileName;
  14.     string storeText;
  15.     bool r = false;
  16.  
  17.     cout << "What file do you want to open?" << endl;
  18.     cout << "The file you want to open must be typed in EXACTLY as it" << endl;
  19.     cout << "appears on your computer; for example: document.txt" << endl;
  20.     cout << "Enter file name: ";
  21.  
  22.     getline(cin, fileName);
  23.  
  24.     if(fileName == "updatehistory")
  25.     {
  26.         updateHistory(r);
  27.     }
  28.     if(r == true)
  29.     {
  30.         cout << "Enter file name: ";
  31.         getline(cin, fileName);
  32.     }
  33.  
  34.     ifstream fileIn;
  35.     fileIn.open(fileName.c_str());
  36.  
  37.     cout << "\n";
  38.  
  39.     if(fileIn.fail())
  40.     {
  41.         cout << "Failed to open" << endl;
  42.         fileIn.close();
  43.     }
  44.  
  45.     stringstream ss(stringstream::app | stringstream::out);
  46.  
  47.     while(getline(fileIn, storeText))
  48.     {
  49.         ss << storeText << endl;
  50.     }
  51.     cin.ignore();
  52.     storeText = ss.str();
  53.  
  54.     find(storeText, fileIn);
  55.  
  56.     fileIn.close();
  57. }
  58.  
  59. int find(string& storeText, ifstream& fileIn)
  60. {
  61.     size_t found;
  62.     string str2;
  63.     string str3;
  64.     found = storeText.find(str2);
  65.  
  66.     cout << storeText << endl;
  67.  
  68.     if(found == string::npos)
  69.     {
  70.         cout << "Error" << endl;
  71.         return 0;
  72.     }
  73.  
  74.     cout << "Which word you want to find from the document?: ";
  75.     getline(cin,str2);
  76.  
  77.     cout << "Enter a word that will replace it: ";
  78.     getline(cin,str3);
  79.  
  80.     cout << "After replacing with the given word: \n" << endl;
  81.     storeText.replace(storeText.find(str2), str2.length(), str3);
  82.  
  83.     cout << storeText << endl;
  84.     cin.ignore();
  85. }
  86.  
  87. bool updateHistory(bool& r)
  88. {
  89.     cout << "VERSION INFORMATION\n" << endl;
  90.  
  91.     cout << "Version: 1.0.0 Alpha" << endl;
  92.     cout << "Recently added features" << endl;
  93.     cout << "1. Added find and replace function" << endl;
  94.     cout << "   However it currently only can do 1 tem at a time" << endl;
  95.  
  96.     cin.get();
  97.     return r = true;
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement