I have this assignment Assignment:
Write a program that prompts the user to input 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 vowels, output the string.
Your program must contain a function to remove all vowels and a function to determine
whether a character is a vowel.
Design Considerations:
1. Your program must have 2 functions.
2. No global variables. All variables must be inside main().
First a side note: your line 14 reads one word only, not a sentence. See getline()
Lets start with "aa". A vowel at start. Line 54 erases it and line 50 advances i, so the second character is never tested and output is "a". Same is in every case that you erase; you ignore the next character.
How about "Phew"? Line 59 replaces tStr with "P". Game over.
Do try a different approach:
1 2 3 4 5 6
string noVowelString (string tStr)
{
std::string result;
// copy (append) characters from iStr into result
return result;
}
Personally I'd prefer to simply create a new string and build it using the old one
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
std::string RemoveVowels(const std::string arg){
std::string out = "";
for (int i=0; i<arg.size(); i++){
switch(tolower(arg[i])){
case'a':
case'e':
case'i':
case'o':
case'u':
break;
default:
out.push_back(arg[i]);
break;
}
}//I've gone noob and can't remember if switch statement need the semi colon?
return arg;
}
hopefully you can understand how this would work?
Instead of editing an existing string and having issues with what happens to the indexes when you remove parts of the string you can build a new string, and only add to it the parts you're interested in.
Strictly speaking this isn't as kind in RAM (although unless the computer is ancient it shouldn't bat an eye still) but it is a much cleaner way i think.
EDIT: being a programmer you'll hopefully learn that their are many ways to tackle a problem, some better than others. Your job as a programmer is to find the best solution for your requirements. (btw theirs nothing wrong with your approach of removing from the string, i personally prefer not dealing with insertion/extraction from strings)