My goal is to write a C++ program that can read a text file and:
* Count the average number of letters/sentence.
* Count the total amount of digits.
The text file would be read with command "./a.out < textfile"
What I've tried so far is to have the program check each character at a time with "cin >> current". I have a while loop. If current hits a punctuation mark, it should increase linecount by 1. It should also be reading for alpha characters, but I'm not sure how to make it count those.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cctype>
usingnamespace std;
int main()
{
int letters; //Total number of letters per sentence
int digits; //Total number of digits
int sentencecount; //Number of sentences
float averageletters; //Average number of letters per sentence
int linecount ; //Count of lines
char current; //Current character
cin >> current;
digits = 0;
letters = 0;
while (cin)
{
if (current == '.' == '!' == '?')
linecount++;
//calcuate averages and other sentence data
//reset sentence data
if (isalpha(current))//repeat for digits
letters++;
cout << "line #" << letters << endl;
cin >> current;
}
return 0;
}
You can use what I call a "frequency hash" to count the frequency of every character in a string and then perform statistics analysis on that.
This can be as simple as
1 2 3 4 5
void freq(std::map<char, int>& m, char c)
{
// Here you can add logic to ignore certain characters, lowercase everything, etc.
m[c] += 1;
}
If the character exists in the map, its count will be incremented by one. If it doesn't exist, the value gets auto-initialized to 0, and then incremented. The slightly safer version to check for a key is to use 'count' -- if (m.count(c) == 0) m[c] = 1;
Working code in action, using an article from the BBC that I just googled. A few characters are apparently not printable (maybe they're the unicode european apostrophes?), but should otherwise work as expected: https://repl.it/repls/WoefulSarcasticHertz