#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;
}
所以我正在尝试用 C++ 编写一个程序,可以交换句子中的声音(通过反转它)。问题是,当我输入“声乐切换测试运行”时,它输出“vucil swatch tst rn”而不是 TIA(我不是美国本土人士,也不是经验丰富的 C++ 开发人员,所以如果有任何混淆,我很抱歉带着我的问题)
我通过在最后一个 for 循环中打印 text[i] 来调试代码,所有声音都存在于向量中
如评论中所述,您在每个循环中都缺少
break
。添加这些中断意味着对于字符串中作为元音的每个字符,我们每次仅添加(或在第二个循环中)从向量中减去一个字符。
#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]);
break;
}
}
}
// 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();
break;
}
}
}
// print the result
std::cout << "the new text is: " << text << std::endl;
return 0;
}
$ ./a.out
input the text: vocal switch test run
the new text is: vucel switch tast ron