/* Illustrate using strings with functions */ #include #include #include #include using namespace std; void change(string&); int printmenu(); void replacetext(string&); int main() { string line; // open files for reading and writing ifstream infile("filetoedit.txt"); if (!infile) { cout << "filetoedit.txt did not open, exiting.\n"; exit (EXIT_FAILURE); } ofstream outfile("edited.txt"); if (!outfile) { cout << "edited.txt did not open, exiting.\n"; exit (EXIT_FAILURE); } while(getline(infile, line)){ cout << "The next line from the file is: " << endl << line << endl; change(line); outfile << line << endl; } infile.close(); outfile.close(); return 0; } // pass by reference void change(string& line) { //cout << "in change, param is: "<< str << endl; int choice; do { choice=printmenu(); switch(choice) { case 1: //erasetext(line); break; case 2: //inserttext(line); break; case 3: replacetext(line); break; case 4: break; default: cout << "invalid choice, try again." << endl; } // end switch } while (choice != 4); } int printmenu() { int chc; cout << "Enter: \n 1: to erase\n 2: to insert\n 3: to replace\n"; cout << " 4: to move to next line\n"; cin >> chc; return chc; } // input: a string passed by reference // process: asks the user what text to replace // find the position of the text // replace with user's new string // output: the parameter string edited void replacetext(string &str) { string oldsub, newsubstr; cout << "What substring do you want to replace? "; cin >> oldsub; string::size_type index=str.find(oldsub,0); // if the substring is not found, just return if (index==string::npos) { cout << "that substring is not in the line of text" << endl; return; } cout << "Enter the new string: "; cin >> newsubstr; str.replace(index, oldsub.length() ,newsubstr); return; }