問題を解決して、最後の部分に固執しています。ユーザーから5文字を取り出して文字配列に保存し、3文字を入力すると、配列に入力文字が含まれているかどうかを確認します。
たとえば、
ユーザーは5文字を入力します。dagpl
。
2番目の配列subArray
より、メイン配列の文字を今検索するユーザは、3文字の文字を入力しますdgl
。
3文字の結果が見つかりました。これらの3文字を新しい文字に置き換えますか?したがって、3つの新しい置換文字を入力して、ユーザはxyz
と入力します。
最終的なアレイは、xaypz
のように置き換えられます。
古い配列の文字を置換する
文字を置き換えるためのコードが正常に動作しません。何が間違っているのか分かりません。
#include<iostream>
#include<cstdlib>
using namespace std;
int main(int argc, char**argv) {
bool check = false;
char arr[6] = { '\0' };
char subarr[4] = { '\0' };
int count = 0;
cout << "Enter Characters : ";
for (int i = 0; i < 5; i++) {
cin >> arr[i];
}
cout << "Enter 3 Characters and see how many times does array has your Search Characters : ";
for (int i = 0; i < 3; i++) {
cin >> subarr[i];
}
//Sub Array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
if (subarr[i] == arr[j]) {
if (!check) {
cout << "Found characters are: ";
}
count++;
cout << subarr[i] << ",";
check = true;
}
}
}
if (check) {
cout << '\b';
cout << " ";
cout << endl;
}
if (!check) {
cout << "Sorry Nothing Found" << endl;
}
cout << "total Found : " << count << endl;
//SECTION 3
if (check) {
int n = count + 1;
char* replace = new char[n]();
cout << "You can only replace " << count << " new characters because of find operation! so enter it will be replace old array with it: ";
for (int i = 0; i < n - 1; i++) {
cin >> replace[i];
}
//Replace characters
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < 5; j++) {
if (subarr[i] == arr[j]) {
arr[j] = replace[j];
}
}
}
delete[]replace;
replace = NULL;
cout << "New Array would be: ";
for (int i = 0; i < 5; i++) {
cout << arr[i];
}
cout << endl;
}
system("pause");
return EXIT_SUCCESS;
}
実行デバッガでは、それは間違って行く場所を確認するために線でコード行をステップ実行します。何かが私に言わせると、それはあなたが「境界を越えて*」置き換えてインデックス付けすることと関係があるかもしれません。 –
@JoachimPileborg最初の配列には5文字しか入力できません。 –
検索では3文字しか入力できません。つまり、 'count'は* most *' 3'でしょうか?そして、置換ループでは、索引 'j'を使用します。これは' 4 'になります。これは範囲外である可能性があります。ところで、 'arr'のインデックスは* 5 *まで上がってはいけませんか?それは* replace *が範囲外にインデックスされることを保証します*。 –