In: Computer Science
For this exercise, you will receive two string inputs, which are the names of the text files. You need to check if the input file exists. If input file doesn't exist, print out "Input file does not exist."
You are required to create 4 functions:
void removeSpace (ifstream &inStream, ofstream &outStream): removes white space from a text file and write to a new file. If write is successful, print out "Text with no white space is successfully written to outFileName."
int countChar (ifstream &inStream): returns number of character in input file.
int countWord(ifstream &inStream): returns number of words in input file.
int countLines(ifstream &inStream): returns number of lines in input file.
After calling each function, you have to reset the state flags and move the stream pointer to beginning of file. You can do that by closing and re-opening the file, or by calling member functions:
inStream.clear(); inStream.seekg(0);
Example:
Input: input.txt output.txt
Output:
Text with no white space is successfully written to output.txt.
Number of characters is: 154
Number of words is: 36
Number of lines is: 10
If you have any doubts, please give me comment...
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void removeSpace(ifstream &inStream, ofstream &outStream);
int countChar(ifstream &inStream);
int countWord(ifstream &inStream);
int countLines(ifstream &inStream);
int main()
{
string inp_fname, out_fname;
cout << "Enter input filename: ";
cin >> inp_fname;
cout << "Enter output filename: ";
cin >> out_fname;
ifstream in;
in.open(inp_fname.c_str());
if (in.fail())
{
cout << "Input file does not exist." << endl;
return -1;
}
ofstream out;
out.open(out_fname.c_str());
removeSpace(in, out);
cout<<"Text with no white space is successfully written to "<<out_fname<<"."<<endl;
cout<<"Number of characters is: "<<countChar(in)<<endl;
cout<<"Number of words is: "<<countWord(in)<<endl;
cout<<"Number of lines is: "<<countLines(in)<<endl;
return 0;
}
void removeSpace(ifstream &inStream, ofstream &outStream){
inStream.clear();
inStream.seekg(0, ios::beg);
char ch;
while(inStream>>ch){
outStream<<ch;
}
}
int countChar(ifstream &inStream){
inStream.clear();
inStream.seekg(0, ios::beg);
int count = 0;
string line;
while(!inStream.eof()){
getline(inStream, line);
count += line.size();
}
return count;
}
int countWord(ifstream &inStream){
inStream.clear();
inStream.seekg(0, ios::beg);
int count = 0;
string word;
while(!inStream.eof()){
inStream>>word;
count++;
}
return count;
}
int countLines(ifstream &inStream){
inStream.clear();
inStream.seekg(0, ios::beg);
int count = 0;
string line;
while(!inStream.eof()){
getline(inStream, line);
count++;
}
return count;
}