Simple C++ problem

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.

Anyway here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <string>

using namespace 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')
	{
		return true;
	}
	else
	{
		return false;
	}
}


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.

Thank you in advance for the help! :)
Last edited on
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).

Last edited on
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.
Last edited on
Topic archived. No new replies allowed.