Pointers and Dynamic Memory, C++ Write a function that will take a string and re
ID: 3778051 • Letter: P
Question
Pointers and Dynamic Memory, C++
Write a function that will take a string and return a count of each letter in the string. For example, "my dog ate my homework" contains 3 m's, 3 o's, 2 e's, 2 y's and one each of d, g, a, t, h, w, r and k. 2 Your function should take a single string argument and return a dynamically allocated array of 26 integers representing the count of each of the letters a . . z respectively. Your function should be case insensitive, i.e., count 'A' and 'a' as the occurrence of the letter a. [Hint: use the letter to integer conversion functions.] Do not count non-letter characters (i.e., spaces, punctuation, digits, etc.) Write a program that will solicit a string from the user using getline, call your letter frequency function and print out the frequency of each letter in the string. Do not list letters that do not occur at least once. Example: Enter a string: my dog at my homework Letter frequency
a 1
d 1
e 1
g 1
h 1
k 1
m 3
o 3
r 1
t 1
w 1
y 2
Explanation / Answer
#include <iostream>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
int i;
char *str;
size_t bufsize = 32;
size_t characters;
void count_function(); // declaration
int counts[26] ={0}; // count array
int main()
{
str = (char *)malloc(bufsize * sizeof(char));
cout<<"Type something: ";
characters = getline(&str,&bufsize,stdin);
count_function(); // letter counting function call
}
// function definition
void count_function()
{
for (i=0;i<bufsize;i++)
{
char c = str[i];
if (!isalpha(c)) continue;
counts[(int)(tolower(c) - 'a')]++;
}
for (i=0;i<26;i++)
{
printf("'%c' has %2d occurrences. ", i + 'a',counts[i]);
}
}
example
example:
Type something: My dog ate my homework
'a' has 1 occurrences.
'b' has 0 occurrences.
'c' has 0 occurrences.
'd' has 1 occurrences.
'e' has 2 occurrences.
'f' has 0 occurrences.
'g' has 1 occurrences.
'h' has 1 occurrences.
'i' has 0 occurrences.
'j' has 0 occurrences.
'k' has 1 occurrences.
'l' has 0 occurrences.
'm' has 3 occurrences.
'n' has 0 occurrences.
'o' has 3 occurrences.
'p' has 0 occurrences.
'q' has 0 occurrences.
'r' has 1 occurrences.
's' has 0 occurrences.
't' has 1 occurrences.
'u' has 0 occurrences.
'v' has 0 occurrences.
'w' has 1 occurrences.
'x' has 0 occurrences.
'y' has 2 occurrences.
'z' has 0 occurrences.