Write a program that asks the user for a file name and displays the content of t
ID: 3680829 • Letter: W
Question
Write a program that asks the user for a file name and displays the content of the file with the line number first, then displays the number of characters (including all characters such as letters, digits, space, newline characters), the number of non-whitespace characters, words, and lines in that file. Then have the program ask for the name of the next file. When the user enters a file that doesn't exist, the program should exit. Note that white Space is defined as any character or series of characters that represent horizontal or vertical space in typography. With many keyboard layouts, a horizontal whitespace character is the "spacebar" key or "tab" key, and a vertical white space is the "enter" key, which creates a newline character. The nonwhitespace character is any character, which is not a white space character. You can download two text files named count_me.txt and count_you.txt from CS215 course web page, and save them into the same folder where you save your C++ source file. Then test your program with these two text files. You can create your own text file and test your program with your own created text file as well. The following is the sample output of running your program: Enter filename: count_me.txt Line 1 : There are only 10 kinds of people Line 2 : in this world: Line 3 : those who know binary and those who do not. The file contains: 93 characters, 74 non-whitespace characters, 19 words, 3 lines.Explanation / Answer
#include <iostream.h>
#include <fstream.h>
#include <string.h>
//using namespace std;
int main()
{
int c=1;
char ch,c;
int count=1;
int i=0;
int count1=1;
string filename;
cout<<"Please enter the data file name: ";
// reads the filename from the user
cin>>filename;
// open the file for input.
ifstream infile(filename, std::ifstream::in);
// create the stream in read-only mode
if(!infile) {
cout << "Cannot open file for reading. ";
_getch();
return 1;
}
string s;
while(infile)
{
getline(f, s);
cout<<"Line "+c+" : "+s<<endl;
c++;
}
// declares character and integer variables
// running the loop until file will end
while(infile.get(ch))
{
cout<<ch;
if(ch==' ')
{
count++;
count1++;
}
else if(ch==' ')
count1++;
i=i+1;
}
cout<<"";
// display the number of character, words and line
cout<<" Number of characters: "<<i-(count-1+count1-1)<<"";
cout<<" Number of words: "<<count1<<"";
cout<<" Number of lines: "<<count<<"";
// closes the file
infile.close();
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.