In: Computer Science
For the following code I need to open the file of a persons choice which I did. I can get it to read the file, but I need help with counting lines and characters feel like i have the code I just cant make it work.
Either way, the program should then ask the user Analyze another file (y/n)? and repeat the process again (asking for a file and analyzing its meta-data). This should continue repeating until the user chooses n for not analyzing another file.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int lines, chars;
string file, text;
fstream reader;
char choice;
string line;
int count = 0;
string L;
do{
cout << "File to open:\n";
getline(cin, file);
ifstream ReadFile;
ReadFile.open(file);
if(ReadFile.fail())
{
// output after failing at opening file
cout << "Clould not open file." << endl;
}
else
{
for(string words; getline(ReadFile, words, '.'); ) //read sentences including
//spaces
cout<<words; //Display sentences
while( getline (ReadFile, line)){ //gets the # of chars
cout<<line<<endl;
chars++;
}
while ( getline (file, L))
count++;
// output after analyzing a file
cout << "Lines: " << L << endl;
cout << "Characters: " << chars << endl;
}
ReadFile.close();
// prompt user whether they want to repeat
cout << "Analyze another file (y/n)?" << endl;
cin >> choice;
cin.ignore();
}while( choice==y);
return 0;
}
Code:
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
int main() {
char ch;
string file,line;
fstream reader;
char c;
ifstream ReadFile;
do{
int count_line = 0,count_word=0;
cout << "File to open:\n";
fflush(stdin); //used to flush the output buffer of the stream
getline(cin, file);
ReadFile.open(file.c_str());
if(ReadFile.fail()) // output after failing at opening file
{
cout<<"Clould not open file."<<endl;
}
else
{
while (getline(ReadFile, line))
count_line++; //count number of lines
ReadFile.clear(); //return file pointer to first position of the file
ReadFile.seekg(0);
while (1)
{
ReadFile.get(c);
if (ReadFile.eof()) break;
count_word++; //count number of charecter including space
}
ReadFile.close(); //close the file
}
// output after analyzing a file
cout << "Lines: " << count_line << endl;
cout << "Characters: " << count_word << endl;
cout << "Analyze another file (y/n)?" << endl; // prompt user whether they want to repeat
cin>>ch;
}while(ch=='y');
return 0;
}
Testing file:
Output: