Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Ch10 Strings.cpp:: Created by Tae Soo Kim
- #include <iostream>
- int receiveString(char*& cString);
- int countVowels(char* cString, int size);
- int countConsonants(char* cString, int size);
- using namespace std;
- int main()
- {
- char* cString = nullptr;
- //the function returns size in order to dynamically allocate the size of the char array off the alphabet.
- //can't use strlen on a pointer to a c-string therefore we need the size.
- // for the pointer, we can just pass it by reference to the function in order to pass it by reference onto the program.
- int size = receiveString(cString);
- //C-String is created
- //Start the menu
- //Initialize input as 'F'
- char input = 'F';
- while (input != 'e' && input != 'E') {
- cout << "A) Count the vowels in the string" << endl;
- cout << "B) Count the consonants in the string" << endl;
- cout << "C) Count both vowels and consonants in the string" << endl;
- cout << "D) Enter another string" << endl;
- cout << "E) Exit this program" << endl;
- cin >> input;
- if (input == 'a' || input == 'A') {
- cout << "The string has " << countVowels(cString, size) << " vowels." << endl << endl;
- }
- else if (input == 'b' || input == 'B') {
- cout << "The string has " << countConsonants(cString, size) << " consonants." << endl << endl;
- }
- else if (input == 'c' || input == 'C') {
- cout << "The string has " << countVowels(cString, size) << " vowels and " << countConsonants(cString, size) << " consonants." << endl << endl;
- }
- else if (input == 'd' || input == 'D') {
- // Enter another string
- cin.ignore();
- size = receiveString(cString);
- }
- }
- }
- int receiveString(char*& cString) {
- // Create an alphabet array, initialize to 0
- int alphabet[256] = { 0 };
- cout << "Enter a string: ";
- int size = 0;
- /*cin.ignore();*/
- char inputChar = cin.get();
- // While not null (end of str)
- while (inputChar != 10) {
- size++;
- int aChar = inputChar;
- alphabet[aChar]++;
- inputChar = cin.get();
- }
- //Received input
- //Now create the C-String
- cString = new char[size];
- int cStrInputIdx = 0;
- for (int i = 0; i < 256; i++) {
- // if we have letter
- while (alphabet[i] != 0) {
- char alphaChar = (char)i;
- cString[cStrInputIdx] = alphaChar;
- alphabet[i]--;
- cStrInputIdx++;
- }
- }
- return size;
- }
- int countVowels(char* cString, int size) {
- int vowels = 0;
- for (int i = 0; i < size; i++) {
- if (cString[i] == 'a' ||
- cString[i] == 'A' ||
- cString[i] == 'e' ||
- cString[i] == 'E' ||
- cString[i] == 'i' ||
- cString[i] == 'I' ||
- cString[i] == 'o' ||
- cString[i] == 'O' ||
- cString[i] == 'u' ||
- cString[i] == 'U') {
- vowels++;
- }
- }
- return vowels;
- }
- int countConsonants(char* cString, int size) {
- //subtract size from vowels
- int vowels = countVowels(cString, size);
- return size - vowels;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement