读书人

字符串连接,该怎么处理

发布时间: 2013-10-21 17:02:52 作者: rapoo

字符串连接
//strcat是我自己编写一个函数,用来完成字符串连接功能,字符串位数最多为12位
#include <stdio.h>
#include <stdlib.h>

char *strcat( char *input, const char *suffix )
{
int length = 0;
while( *input && length < 11 )
{
input++;
length++;
}

while( *suffix && length < 11)
{
length ++;
*input = *suffix;
input++;
suffix++;
}
*input = '\0';

return input;
}

int main( void )
{
char buff[ 12 ];
//char *input;

puts( "Please input a string" );
gets( buff );

puts( strcat( buff, ".exe" ) );
//printf( "The final string is ", strcat( input, ".exe" ) );

system( "pause" );
return 0;
}
可是为什么打印不出来连接后的字符串呢?谢谢!
[解决办法]
return input; 时 input 已经指向 '\0' 了,当然什么都不显示了。
[解决办法]
修改如下



char *strcat( char *input, const char *suffix )
{
int length = 0;
char *temp;
temp=input;

while( *temp && length < 11 )
{
temp++;
length++;
}

while( *suffix && length < 11)
{
length ++;
*temp = *suffix;
temp++;
suffix++;
}
*temp = '\0';

return input;
}

[解决办法]
你的主要问题是修改了input所指向的起始地址,
还有建议你自定义的函数不要和标准库里的函数同名,修改下函数名

读书人网 >C++

热点推荐