Can anyone help me with C++ program which receives a file name as command line argument, reads all the lines of text in the input file, and prints out the longest line in the file.
If there are multiple lines of the same length, the first longest line should be returned. If the input file is empty (does not contain any lines) then the program should not print anything.
Don’t need to be the full code, just a general frame/algorithm is good enough. thx!
Expert Answer
Program:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(int argc, char** argv)
{
ifstream inFile;
char* filename;
filename = argv[0];
string line;
inFile.open(“C:\Users\Sandeep\Desktop\sample.txt”);
int length = 0;
string longest;
if (inFile.is_open())
{
while ( getline (inFile,line) )
{
if(line.length()>length){
length = line.length();
longest = line;
}
}
inFile.close();
cout<<“nLongest line : “<<longest;
}
else cout << “Unable to open file”;
return 0;
}
Output: