1.
Write a program that takes in an input file called
and prints the first 5 lines to the terminal. Include proper file error checking.
poem.txt
1
Data: poem.txt
Two roads diverged in a yellow wood, And sorry I could not travel both And be one traveler, long I stood And looked down one as far as I could To where it bent in the undergrowth; Then took the other, as just as fair, And having perhaps the better claim Because it was grassy and wanted wear, Though as for that the passing there Had worn them really about the same, And both that morning equally lay In leaves no step had trodden black. Oh, I kept the first for another day! Yet knowing how way leads on to way I doubted if I should ever come back. I shall be telling this with a sigh Somewhere ages and ages hence: Two roads diverged in a wood, and I, I took the one less traveled by, And that has made all the difference.
Solution.
Below is one way to implement this program. We create an
ifstream
object to open our file. We check to make sure the file is opened correctly before we use getline
in a for
loop to retrieve and print the first 5 lines of the poem.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream infile("poem.txt");
string input;
if (!infile.good()) {
cout << "Error. Unable to open file." << endl;
exit(1);
}
for (int i = 0; i < 5; ++i) {
getline(infile, input);
cout << input << endl;
}
}