Create a C++ program which inputs the name of a simple text file from the user (
ID: 3817663 • Letter: C
Question
Create a C++ program which inputs the name of a simple text file from the user (e.g. user.txt) and prints the first 10 lines of the file to the screen. If the file contains less than 10 lines, then simply print the entire file to the screen. Your program should check for failure after opening the file. If the “open” fails, print a descriptive message for the user.
You will need to create a text file in the same folder as your code. Download a file of text from http://gutenberg.org (Links to an external site.). Your program must validate the filename for the .txt extension, and must check for an error condition when opening the file.
Your program must use one input function, at least one processing function (using an "open" ifstreamvariable as a parameter), and at least one output function.
Explanation / Answer
#include<iostream>
#include <fstream>
#include<string>
using namespace std;
string input() { //reads filename from user
string fileName;
cout<<"Enter file name: ";
cin>>fileName;
return fileName;
}
string process(ifstream &inputFileStream) { //function to process the file and extract 10 lines of data from the file
int lineCount = 0;
string line;
string data = "";
while (lineCount < 10 && getline(inputFileStream, line)) { //while loop stops either if 10 lines are read or ran out of data in file
data = data + line + " ";
lineCount ++;
}
return data; //return captured data
}
bool validateFile (string fileName) { //function to chk if the extention is .txt
if(fileName.substr(fileName.find_last_of(".") + 1) == "txt")
return true;
return false;
}
int main() {
ifstream istream;
string infile = input();
if (validateFile(infile)) {
istream.open(infile.c_str()); // to convert string to char array
if (istream.is_open()) {
string out = process(istream);
cout<<out;
}
else
cout<<"Cannot Open file ";
}
else
cout<<"The file name you entered is not compatable ";
return 0;
}
Here you go champ. I kept the code very simple so that yu don't face any problem understanding. For you ease i have even commented the code. If incase you find any difficulty understanding the code, please feel free to comment below.