Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <fstream>
- #include <vector>
- using namespace std;
- void readFile();
- int main(){
- cout << "Would you like to create or read a file? (type: 'create' or 'read'): ";
- string uDesc;
- cin >> uDesc;
- if(uDesc == "create"){
- vector<string> userData;
- cout << "Enter what you want to name the file (Must be .txt): ";
- string fileName;
- cin >> fileName;
- ofstream myFile(fileName);
- if(myFile.is_open()){
- cout << "Enter number of words (Must press ENTER after each word): ";
- int wordCount;
- cin >> wordCount;
- for(int i = 0; i < wordCount; i++){
- cout << "Enter word " << i + 1 << ": ";
- string uInput;
- cin >> uInput;
- userData.push_back(uInput);
- userData.push_back(" ");
- }
- for(unsigned int i = 0; i < userData.size(); i++){
- myFile << userData[i];
- cout << endl;
- cout << "Data: '" << userData[i] << "' successfully written" << endl;
- }
- myFile.close();
- cout << endl;
- cout << "----------------------------------------------" << endl;
- cout << "All text to " << fileName << " has been successfully written" << endl;
- cout << endl;
- cout << "Would you like to read from a file? (yes or no): ";
- string yOr;
- cin >> yOr;
- if(yOr == "yes"){
- readFile();
- }else{
- cout << "Completed" << endl;
- }
- }else{
- cout << "Could not open file" << endl;
- }
- }else if(uDesc == "read"){
- readFile();
- }else{
- cout << "Invalid option" << endl;
- }
- system("pause");
- return 0;
- }
- void readFile(){
- vector<string> fileText;
- cout << "Name of file: ";
- string fileName;
- cin >> fileName;
- cout << "Look for a certain word? (yes or no): ";
- bool wordSearch = false;
- string yesOrNo;
- string specWord;
- cin >> yesOrNo;
- if(yesOrNo == "yes"){
- wordSearch = true;
- cout << "What word?: ";
- cin >> specWord;
- }else{
- wordSearch = false;
- }
- ifstream myFile;
- myFile.open(fileName);
- string fileData;
- int fileSize = 0;
- int specCount = 0;
- cout << endl;
- cout << "Data from " << fileName << ": ";
- while(!myFile.eof()){
- fileSize++;
- myFile >> fileData;
- cout << fileData;
- cout << " ";
- if(wordSearch == true){
- if (fileData == specWord){
- specCount++;
- }
- }
- }
- cout << endl;
- cout << endl;
- cout << endl;
- cout << "-----------------------------";
- cout << endl;
- cout << fileSize << " words found and displayed" << endl;
- cout << "-----------------------------" << endl;
- cout << endl;
- cout << "-----------------------------" << endl;
- if(wordSearch == true){
- cout << specWord << " was found " << specCount << " times" << endl;
- cout << "-----------------------------" << endl;
- cout << endl;
- }
- myFile.close();
- }
Add Comment
Please, Sign In to add comment