ユーザーに単語または文を入力するように求め、単語/文を調べ、「a」または「A」のすべてのインスタンスを「aoa」または「AoA」に置き換えてから結果を出力する C++ プログラムを作成しています。ただし、長い文を入力しようとすると問題が発生します。たとえば、「なぜプログラムが動作しないのか」と入力すると、プログラムは期待される結果ではなく、奇妙な文字を出力します。これは私のコードです:
#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;
}
問題の原因は何ですか?