新微赢技术网

标题: 一个字符串函数的困惑! [打印本页]

作者: 水清苓    时间: 2009-11-4 00:13
标题: 一个字符串函数的困惑!
strncpy(name ,pName,sizeof(name));
这个函数是干什么的?
如何使用能否举例说明?
作者: ●.涛涛"★    时间: 2009-11-4 00:13
把pName复制到name中,复制字符个数是sizeof(name).
#include<iostream.h>
#include<string.h>
int main()
{
char name[11];
char pName[11]="my name is";
strncpy(name ,pName,sizeof(name));
cout<<name<<endl;
return 0;
}
  我也刚学
作者: 红苹果    时间: 2009-11-4 00:13
#include <iostream>
#include <cstring>
int main( void )
{
char a[20] = "test";
char s[20];
// simple strncpy usage:
strcpy( s, "dogs like cats" );
printf( "Original string:\n '%s'\n", s );
strncpy( s, "mice", 4 );
printf( "After strncpy (no null-termination):\n '%s'\n", s );
strncpy( s+5, "love", 4 );
printf( "After strncpy into middle of string:\n '%s'\n", s );
strncpy( s, "mice", 6 );
printf( "After strncpy (with null-termination):\n '%s'\n", s );
}

Output
Original string:
'dogs like cats'
After strncpy (no null-termination):
'mice like cats'
After strncpy into middle of string:
'mice love cats'
After strncpy (with null-termination):
'mice'


The strncpy function copies the initial count characters of strSource to strDest and returns strDest. If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. If count is greater than the length of strSource, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap.




欢迎光临 新微赢技术网 (http://bbs.weiying.cn/) Powered by Discuz! X3.2