I'm trying to write a program in C++ that can swap the vocals on a sentence (by reversing it).
#include <iostream>
#include <string>
#include <vector>
int main() {
// declare the variables
std::string text;
char vocals[] = {'a', 'i', 'u', 'e', 'o', 'A', 'I', 'U', 'E', 'O'};
// get the input
std::cout << "input the text: ";
std::getline(std::cin, text);
// declare the vector to store the vocals
std::vector<char> v(text.length());
// identify the vocals
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < 10; j++) {
if (text[i] == vocals[j]) {
v.push_back(text[i]);
}
}
}
// swap the vocals
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < 10; j++) {
if (text[i] == vocals[j]) {
text[i] = v.back();
v.pop_back();
}
}
}
// print the result
std::cout << "the new text is: " << text << std::endl;
return 0;
}
The problem is, when I input "vocal switch test run", it outputs "vucil swatch tst rn" instead.
I debugged the code by printing text[i] in the last for loop, all the vocals are present in the vectors.
As noted in comments, you're missing a
breakin each of your loops. Adding these breaks means that for each character in the string that is a vowel, we only add (or in the second loop) subtract one character at a time from the vector.Taking greater advantage of the STL, I might write the following, using a
is_vowelfunction that leveragesstd::set<char>andstd::copy_ifas well as a range-based for loop.