In C++, Write a program to read in a simple text file (let\'s call it \"simplefi
ID: 3780857 • Letter: I
Question
In C++, Write a program to read in a simple text file (let's call it "simplefile.txt") and:
find the number of characters in each word (save those values as a variable called "word"), the number of characters in each line (save those values as a variable called "line"), the number of characters in each sentence (save those values as a variable called "sent"), and the number of characters in each paragraph (save those values as a variable called "para").Please make the program as simple as possible and include comments illustrating the logic behind each step.
Explanation / Answer
#include<iostream.h>
#include<fstream.h>
#include<string.h>
#include<conio.h>
#include<stdio.h>
void countchar(char *filename)
{
ifstream fin(filename);
char ch;
std::string line;
int i,words=0,sent=0,lines=0;
int wc=0, lc=0, sc=0;
bool l=false, s=false;
while(fin.get(ch))
{
i=ch;
//cout<<ch;
if(i==' ')
{
words++;
cout << " word no "<<words<<" contains "<<wc<<" characters"<<endl;
wc=0;
}
else if (i == ' ')
{
// check if sentence is complete then count only line and not words
if(!s)
{
words++;
cout << "Word no "<<words<<" contains "<<wc<<" characters"<<endl;
wc=0;
}
lines++;
cout << "Line no "<<lines<<" contains "<<lc<<" characters"<<endl;
lc=0;
s=true;
}
else if (i == '.') // if character is . this marks end of sentence so display characters in sentence
{
words++;
cout << " word no "<<words<<" contains "<<wc<<" characters"<<endl;
wc=0;
sent++;
cout << "Sentence no "<<sent<<" contains "<<sc<<" characters"<<endl;
sc=0;
s=true;
}
else
{
wc++; lc++; sc++;
}
}
fin.clear();
}
int main()
{
char *filename="sent.txt";
char a;
countchar(filename);
return 0;
getch();
}
// Regarding paragraph, it depends on how you view paragraph. Isit new line or one empty line in between. Usually paragraphs start in new line so in that case.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.