In: Computer Science
Write a program that reads and prints a joke and its punch line from two different files. The first file contains a joke, but not its punch line. The second file has the punch line as its last line, preceded by “garbage.” The main function of your program should open the two files then call two functions, passing each one the file it needs. The first function should read and display each line in the file it is passed (the joke file). The second function should display only the last line of the file it is passed (the punch line file). It should find this line by seeking to the end of the file and then backing up to the beginning of the last line. Data to test your program can be found in the joke.txt and punchline.txt files. the programming language is c++
#include <iostream> #include <fstream> using namespace std; void printJoke(string fileName) { ifstream f; f.open(fileName.c_str()); if(f.is_open()) { string line; while (getline(f, line)) { cout << line << endl; } f.close(); //closes the input } } void printPunchLine(string fileName) { ifstream f; f.open(fileName.c_str()); if(f.is_open()) { f.seekg(-1,ios_base::end); // go to one spot before the EOF bool keepLooping = true; while(keepLooping) { char ch; f.get(ch); // Get current byte's data if((int)f.tellg() <= 1) { f.seekg(0); keepLooping = false; } else if(ch == ' ') { keepLooping = false; } else { f.seekg(-2,ios_base::cur); } } } string lastLine; getline(f,lastLine); cout << lastLine << ' '; f.close(); } int main() { printJoke("joke.txt"); printPunchLine("punchline.txt"); }
Please upvote, as i have given the exact answer as asked in
question. Still in case of any concerns in code, let me know in
comments. Thanks!