下面代碼為什么會提示沖突int replace(char*str, char c1, char c2) {int count = 0;int i = 0;while (*str != '\0') {if (str[i] = c1){str[i] = c2;count++;}i++;}return count;}int main(){char A[5] = "abcd";cout << "count:" << replace(A, 'a', 'f') << endl << "A" << A;return 0;}
2 回答
紅糖糍粑
TA貢獻1815條經驗 獲得超6個贊
1、星str表示char數組的第一個元素,所以永遠不可能=\0,while死循環,i一直自增,str[i]越界
2、str[i] = c1;是賦值,str[i] = =c1才是判斷
蕪湖不蕪
TA貢獻1796條經驗 獲得超7個贊
來,給你改了一下,運行試試:
int replace(char*str, char c1, char c2) {
int count = 0;
int i = 0;
while (str[i] != '\0') {
if (str[i] == c1){
str[i] = c2;
count++;
}
i++;
}
return count;
}
int main()
{
char A[5] = "abcd";
cout << "count:" << replace(A, 'a', 'f') << endl << "A:" << A;
return 0;
}- 2 回答
- 0 關注
- 716 瀏覽
添加回答
舉報
0/150
提交
取消
