我正在写一个简单的字符串替换函数,我有一个相当有趣的错误。不应该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