Write a program in C++ that asks the user for the name of a file, a starting lin
ID: 3912865 • Letter: W
Question
Write a program in C++ that asks the user for the name of a file, a starting line number and an ending line number. The program should display the contents of the file on the screen beginning with the starting line number and stopping with the ending line number. If the program encounters the end of the file, it should display a blank line followed by the text: [END OF FILE]
Input validation:
- Do not accept negative line numbers
- Do not accept an ending line number less than the starting line number.
Explanation / Answer
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts. Thanks
//Code
#include<iostream>
#include<fstream>
using namespace std;
int main(){
string filename;
cout<<"Enter file name: ";
//getting file name
cin>>filename;
int startingLine=-1,endingLine=-1;
//looping until a valid starting and ending line values are given
while(startingLine<0 || startingLine>endingLine){
cout<<"Enter starting line number: ";
cin>>startingLine;
cout<<"Enter ending line number: ";
cin>>endingLine;
if(startingLine<0){
cout<<"line number cannot be negative"<<endl;
}
if(startingLine>endingLine){
cout<<"Starting line number should be less than ending line number"<<endl;
}
}
//defining an ifstream object to open the file for reading
ifstream inFile(filename.c_str());
if(!inFile){
//couldnt open
cout<<"File not found/not readable"<<endl;
}else{
int i=1;
string line;
//moving the cursor until the specified starting line is found
while(i<startingLine){
if(!getline(inFile,line)){ //fetching a line of text
//end of file reached while traversing
cout<<endl<<"[END OF FILE]"<<endl;
//quitting
return 0;
}
i++;
}
cout<<" Contents between line "<<startingLine<<" and "<<endingLine<<": "<<endl;
//now displaying the lines until end of line value is reached for i.
while(i<=endingLine){
if(!getline(inFile,line)){
//end of file reached, no more lines
cout<<endl<<"[END OF FILE]"<<endl;
return 0;
}else{
cout<<line<<endl;
}
i++;
}
}
}
//data.txt
this is some random textfile
containing
different lines
line 4
line 5
line 6
another line
yet another line
ok! thats it.
final data :P
//output1
Enter file name: data.txt
Enter starting line number: -6
Enter ending line number: 6
line number cannot be negative
Enter starting line number: 6
Enter ending line number: 9
Contents between line 6 and 9:
line 6
another line
yet another line
ok! thats it.
//output2
Enter file name: data.txt
Enter starting line number: 5
Enter ending line number: 15
Contents between line 5 and 15:
line 5
line 6
another line
yet another line
ok! thats it.
final data :P
[END OF FILE]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.