I am trying to write a program that will count the number of words, and number of sentences, and then take the average of those sentences. It takes the input from a user and will stop taking the input upon seeing "@@@". My code is as follows:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
using namespace std;
int main() ///Main
{
//1. Declaration of variables
string text;
double word_count = 0.0;
double sentence_count = 0.0;
double avg_words_per_sentence;
//2. Prompt user input
cout << "Enter a paragraph..." << endl;
getline(cin, text, '@'); //3. Use getline to read whole paragraph and not first word entered
//4. Loop to read through text inputted and determine number of words and sentences
for (int i = 0; i < text.length(); i++)
{
if (text[i] == ' ')
{
word_count++;
}
else if (text[i] == '.' || text[i] == '!' || text[i] == '?')
{
sentence_count++;
}
}
//5. Provides error if there is no text
if (word_count == 0 && sentence_count == 0)
{
cout << "Word count: " << word_count << endl;
cout << "Sentence count: " << sentence_count << endl;
cout << "You did not enter any text!" << endl;
}
//6. Provides an error if there are no sentences
else if (sentence_count == 0)
{
cout << "Word count: " << word_count + 1 << endl;
cout << "Sentence count: " << sentence_count << endl;
cout << "You did not enter any sentences!" << endl;
}
//7. Calculates and outputs word/sentence count and average # of words
else
{
word_count++;
avg_words_per_sentence = word_count / sentence_count;
cout << "Word count: " << word_count << endl;
cout << "Sentence count: " << sentence_count << endl;
cout << "Average words per sentence: " << fixed << setprecision(1) << avg_words_per_sentence << endl;
}
return 0;
}
For example: If I were to use the input:
ttt
@@@
I would expect my word count to be 1, but I am instead told that it is 2. I am unsure as to why it is counting 2.
I tried tweaking certain if/then statements such as if the string contain "@" to not count the word or only count words if there is a space after a proper character but I am still met with the same incorrect number of words