https://www.dropbox.com/sh/gm5srndm53a7o9s/AACGdSwiXmZdGfQwf2jSHJrQa/Week-09?dl=
ID: 3602067 • Letter: H
Question
https://www.dropbox.com/sh/gm5srndm53a7o9s/AACGdSwiXmZdGfQwf2jSHJrQa/Week-09?dl=0&preview=movies.txt
The program should input the name of the file from the keyboard:
movies.txt
Output should be number of movies, first movie name, and last name movie:
100
The Shawshank Redemption(1994)
Witness for the Prosecution(1957)
PLEASE USE THE FOLLWOWING TEMPLATE:
string moviename;
getline(file, moviename);// read entire line as the movie name:
getline(file, moviename);// read first movie:
while(!file.eof())//while not EOF marker:
{
.
.
.
getline(file, moviename);// read next movie (will be empty string @ EOF):
}
Explanation / Answer
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
string moviename;
ifstream file;
string fileName;
cout << "Enter the name of the file:" << endl;
cin >> fileName;
int totalMovies = 0;
string firstMovie;
string lastMovie;
file.open(fileName.c_str()); //open file
if (!file) { //check if u opened file properly or not
cout << "Error opening "<<fileName << endl;
return 1;
}
getline(file, moviename);
firstMovie = moviename;
lastMovie = moviename;
totalMovies++;
while (!file.eof()) { // read entire line as the movie name:
getline(file, moviename);
if(moviename.length()> 0)
{
lastMovie = moviename;
totalMovies++;
}
}
cout << "Number of movies, first movie name, and last name movie:" << endl;
cout << totalMovies << endl;
cout << firstMovie << endl;
cout << lastMovie << endl;
return 0;
}
=================
Enter the name of the file:
movies.txt
Number of movies, first movie name, and last name movie:
101
The Shawshank Redemption (1994)
Witness for the Prosecution (1957)
============
Thanks
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.