我正在寫一個簡單的字符串替換函數,我有一個相當有趣的錯誤。不應該strcpy只是覆蓋buf \ streamBuf值?它如何連接數組?意外的行爲與strcpy和數組
int main()
{
char buf[512];
strcpy(buf, "Test\nInput\nHere\n");
char fromCh[2] = "\n";
char toCh[4] = "\\n ";
stripChars(buf, fromCh, toCh);
printf("Here's your buf: %s", buf);
return 0;
}
void stripChars(char *streamBuf, char* fromCh, char *toCh){
char strTemp[512];
int i=0;
int iLenFrom = strlen (fromCh);
int iLenTo = strlen (toCh);
while (*streamBuf)
{
if (strncmp (streamBuf, fromCh, iLenFrom) == 0)
{
strncpy (&(strTemp[i]), toCh, iLenTo);
i += iLenTo;
streamBuf += iLenFrom;
}
else
{
strTemp[i++] = *streamBuf;
streamBuf++;
}
}
strTemp[i] = '\0';
strcpy(streamBuf, strTemp);
printf("Here's your strTemp: %s \n", strTemp);
printf("Here's your streamBuf: %s \n", streamBuf);
}
,這裏是我的輸出
Here's your strTemp: Test\n Input\n Here\n
Here's your streamBuf: Test\n Input\n Here\n
Here's your buf: Test
Input
Here
Test\n Input\n Here\n
Process finished with exit code 0
函數:'stripChars()'缺少所需的原型。應該將原型插入文件頂部附近。 – user3629249