Answer to Question #31958 in C++ for Jay

Question #31958
Write a program that asks the user for a file name and displays the number characters, words and lines in that file. Then have the program ask the name of the next file. When the user enters a file that doesn’t exist (such as the empty string), the program should exit.
1
Expert's answer
2013-06-14T09:11:33-0400
#include <iostream>
#include <fstream>
#include <ctype.h>

using namespace std;

bool analysis(char *fileName);

int main(){
char fileName[25];

do{
cout << "Input file name: ";
cin >> fileName;
}
while(analysis(fileName));

return 0;
}

bool analysis(char *fileName){
ifstream f;
f.open(fileName);

if(!f.is_open()){
cout << "File not exist" << endl;
return false;
}

char c;
//possible new word
bool newWord = false;
int numberCharacters = 0, numberLines = 1, numberWord = 0;
while(!f.eof()){
c = f.get();
cout << c;

numberCharacters++;
if('\n' == c)numberLines++;

if( ( (isspace(c)) || (ispunct(c)) ) && (newWord)){
numberWord++;
newWord = false;
}

if(isalpha(c))newWord = true;
}

//if last character in file not space
if(newWord)
numberWord++;

//without EOF character
cout << "Number characters: " << numberCharacters-1 << endl;
cout << "Number lines: " << numberLines << endl;
cout << "Number word: " << numberWord << endl;

f.close();
return true;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS