I am trying to write a program that reads in a line of text and counts the number of words and the number of instances of each letter. After you type in a line of text you hit return and it should give your output. Sometimes if there are some small words, three or less letters, you will need to hit return a second time. It doesn't count all small words. Also the letter count is always the same:
The number of each letter you typed in is:
b 134520536
f 4
h 134520536
l 134520536
p 134520536
q 10
r 4
x 134520536
I had it print out 'c' right after the cin.get statement and it seems to be reading in only every other letter. Any help will be greatly appreciated. Thank you in advance.
Code:
#include <iostream>
#include <cctype>
using namespace std;
void introduction();
//Explains what the program does.
void input_count_output(int& num_words);
//Asks user to input text from the keyboard and then counts
//and outputs to the screen the number of words and the number
//of each letter typed in.
int main()
{
int num_words = 0;
introduction();
input_count_output(num_words);
return 0;
}
//uses iostream
void introduction()
{
cout << "This program will ask the user to input a line of text\n"
<< "and then will output the number of words and the number of\n"
<< "each type of letter.\n"
<< endl;
}
//uses iostrem
//uses string
//uses cctype
void input_count_output(int& num_words)
{
char c;
int letter_count[26];
cout << "Please enter a line of text, then press return:\n";
do
{
cin.get(c);
if (!cin.get(c)) //breaks if character is not able to be read in
break;
if (isalpha(c))
{
if (isupper(c))
c = tolower(c);
}
++letter_count[c - 'a'];
if (c == '\n' || c == '\t' || c == '"' || c == ',' || c == ';' || c == ':' || c == '.' || c == '?' || c == '!' || c == ' ')
++num_words;
}while(c != '\n');
//now for output
cout << "The number of words you typed in is "
<< num_words
<< endl
<< "The number of each letter you typed in is:\n";
for (int i = 0; i < 26; i++)
{
if (letter_count[i] > 0)
{
c = 'a' + i;
cout << c
<< " "
<< letter_count[i]
<< endl;
}
}
}