Hello, I'm practically pulling my hair out because I cant figure this out. My program just won't run the way I intend it to. Oh and before you ask; I know writing the program this way is very silly but my instructor requires us to use the string::substr() function so i did the best I could...
The assignment: Write a program that prompts the user to enter a string. The program then uses the function substr to remove all vowels from the string. For example, if str = "There" then after removing all the vowels str = "Thr". After removing all the vowels, output the string. Your program must contain a function to remove all the vowels and a function to determine whether a character is a vowel.
#include <iostream>
#include <string>
usingnamespace std;
void removeVowels(string& s);
bool isVowel(char v);
int main()
{
string input;
char isRunning = 'y';
cout << "This program will remove all vowels from your input.\n";
while (isRunning != 'n')
{
cout << "Input: ";
cin >> input;
removeVowels(input);
cout << "\nYour new string is: " << input << endl;
cout << "Would you like to go again? <y/n>: ";
cin >> isRunning;
cout << endl;
}
}
void removeVowels(string& s)
{
string tempStr = "";
int substrLength = 0;
int stringStart = 0;
bool startSet = false;
for (int i = 0; i < s.length(); i++)
{
if (!isVowel(s[i]))
{
substrLength++;
if (!startSet)
{
stringStart = i;
startSet = true;
}
}
else
{
tempStr += s.substr(stringStart, substrLength);
substrLength = 0;
stringStart = 0;
startSet = false;
}
}
s = tempStr;
}
bool isVowel(char v)
{
if (v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u' || v == 'A' || v == 'E' || v == 'I' || v == 'O' || v == 'U')
{
returntrue;
}
else
{
returnfalse;
}
}
So, the problem here is the way it's outputting the string. Sometimes it works well and other times not so well. For example, "There" outputs "Thr" as expected, but "dog" outputs only "d" and "aeiouAEIOUH" outputs an empty string.
The problem is that you don't use your substring processing unless you DO find a vowel. As a hack, add s += "e"; to the start of your function - suddenly it will work (I think).
It would probably be cleaner to just check if if startSet is true after the loop is executed. It's clearer than adding a hack. If it's true than you've finished the string without adding the last substring, so go ahead and add it.