我正在解決一個問題,並將其留在最後一部分,現在我正在做什麼。從用戶處取5個字符並將其保存在字符數組中,然後輸入3個字符來檢查數組中是否有輸入字符。
例如:
用戶輸入5個字符dagpl
。
比第二個數組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 *?這將*保證*替換將被索引超出界限。 –