Hello, everyone. I am working on a C++ program that would count the number of sentences from a text file. I know you have to use #include <fstream> and open the file by doing the following
1 2 3 4 5 6 7 8
#include <iostream>
#include <fstream>
usingnamespace std;
int main () {
int total, m;
ifstream myfile ("example.txt");
}
In this case, the end of a senescence means that you have . (period), ? (Question mark), and ! (exclamation point).
Can you please help me how to incorporate that and implement it into C++?
You're on the right track with the checking for a period and so on.
You should read in some amount of text from the file and then check it, one character at a time, for sentence ending punctuation. Every character before that is part of a sentence.
this will read in all the characters until you get to the end of file. you can write if statements if you want it to do something when it encounters a certain character.
I think it's how to access one character at a time. It would check if each character is "." (period), "?" (question), and "!" (exclamation point). If it is one of the followings, it would add counter until the end of the text (there are no more inputs in the text file).
If you use getline you get one string at a time. Loop through that string checking one character at a time. If the character is sentence ending punctuation add one to the sentence count.
Here's some pseudo code to hopefully help get you started.
1 2 3 4 5 6 7 8 9
string currentString;
int sentCount=0;
while(/*able to read into current string*/)
{
for(int i=0;i<currentString.size();i++)
{
//if character i in currentString is a period add one to sentCount
}
}
You should probably stick with what you had before:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
char ch;
//int counter;//Commented this line
int total=0;//Adjusted this line; assigned to 0;
infile.open(fileName, ios::in);
ch = inFile.get();
while (ch != EOF)
{
if (ch == '.' || ch== '!' || ch=='?')//Fixed this line
{
total = total + 1;//Modified this line to correctly use accumulator
}
ch = inFile.get();
cout << "The total number of sentences " << total;
}
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
char ch;
//int counter;//Commented this line
ifstream infile;
int total=0;//Adjusted this line; assigned to 0;
infile.open("example.txt", ios::in);
ch = infile.get();
while (ch != EOF)
{
if (ch == '.' || ch== '!' || ch=='?')//Fixed this line
{
total = total + 1;//Modified this line to correctly use accumulator
}
ch = infile.get();
cout << "The total number of sentences " << total;
}
return 0;
}
This compiles with no error for me; though it has not been tested.
Looks good enough though >.<