Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created November 22, 2023 08:56
Show Gist options
  • Save juanfal/4db122959c392506033ba336df8fe16a to your computer and use it in GitHub Desktop.
Save juanfal/4db122959c392506033ba336df8fe16a to your computer and use it in GitHub Desktop.
string stats
// p6e02.getline.cpp
// juanfc 2023-11-22
//
#include <iostream>
using namespace std;
void stringStat(string s, int& nVow, int& nCons, int& nSpc);
void printStats(string s, int nVow, int nCons, int nSpc);
int main()
{
int nVow, nCons, nSpc;
string s;
cout << "Enter a string, empty to end" << endl;
getline(cin, s);
while (s.length() > 0) {
stringStat(s, nVow, nCons, nSpc);
printStats(s, nVow, nCons, nSpc);
getline(cin, s);
}
return 0;
}
bool isVow(char c);
bool isCons(char c);
bool isSpc(char c);
void stringStat(string s, int& nVow, int& nCons, int& nSpc)
{
nVow = nCons = nSpc = 0;
for (int i = 0; i < s.length(); ++i)
if (isVow(s[i]))
++nVow;
else if (isCons(s[i]))
++nCons;
else if (isSpc(s[i]))
++nSpc;
}
void printStats(string s, int nVow, int nCons, int nSpc)
{
cout << "The string: \"" << s << "\" has:" << endl;
cout << "\tVowels: " << nVow << endl;
cout << "\tConsonants: " << nCons << endl;
cout << "\tSpaces: " << nSpc << endl;
}
bool isVow(char c)
{
return c == 'a' or c == 'e'
or c == 'i' or c == 'o'
or c == 'u';
}
bool isCons(char c)
{
return c > 'a' and c <= 'z'
and not isVow(c);
}
bool isSpc(char c)
{
return c == ' ' or c == '\t'
or c == '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment