我正在编写一个 C++ 程序,它要求用户输入一个单词或句子,遍历单词/句子,用 'aoa' 或 'AoA' 替换所有 'a' 或 'A' 实例,然后输出结果。但是,如果我尝试输入更长的句子,我会遇到问题。例如,如果我输入“程序为什么不运行”,程序会输出奇怪的字母而不是预期的结果。这是我的代码:
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char * argv[])
{
string mening, temp; //The mening string is the word/sentence the user will input.
int play = 1, add;
while (play == 1) {
cout<<"Type in the sentence: ";
getline(cin, mening); //The input is saved in the string variable mening.
unsigned long y = mening.size(); //Grabs the amount of characters in input; this number is saved in the unsigned long variable y.
add = 0; //Makes sure the int variable add is reset to 0 if the loop restarts.
for (int k = 0, n = 1;n<=y;k++, n++) {
if (mening[k] == 'a' || mening[k] == 'A') {
k++;
for (int i = k, m = 1;m<=y - n;i++, m++) {
temp[i] = mening[i];
} //The characters after the one that has been checked are stored in temp array indexes, if the character that has been checked is an a or A.
for (int i = k, m = 1, j = k + 2;m<=y - n;i++, m++, j++) {
mening[j] = temp[i];
} //The characters after the one that has been checked move two steps to the right, to allow the two extra letters.
mening[k] = 'o';
mening[k + 1] = mening[k - 1];
k++;
add = add + 2; //The int variable add is increased by 2 during each aoa/AoA to avoid strange characters being outputted at the very end.
}
else { }
}
for (int k = 0;k<=y + add - 1;k++) {
cout<<mening[k];
}
cout<<endl<<"Do you want to do it again? (yes/no): ";
getline(cin, mening);
cin.clear();
cout << flush;
cout.flush();
cout.clear();
if (mening == "Yes" || mening == "yes" || mening == "YES") {
}
else {
play = 2;
}
}
cout<<endl<<"The program will now close.";
return 0;
}
什么可能导致问题?