标题:一个字符串函数的困惑!
只看楼主
lixang
Rank: 1
等 级:新手上路
帖 子:231
专家分:0
注 册:2006-7-15
 问题点数:0 回复次数:2 
一个字符串函数的困惑!

strncpy(name ,pName,sizeof(name));
这个函数是干什么的?
如何使用能否举例说明?
搜索更多相关主题的帖子: 函数 字符 困惑 name pName 
2006-09-27 15:18
雨夜微醺
Rank: 1
等 级:新手上路
威 望:1
帖 子:147
专家分:0
注 册:2006-9-25
得分:0 

把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;
}
  我也刚学


我若想到你就有种莫名的开心 我一见到你就有种莫名的悸动
2006-09-27 17:13
djx20040701
Rank: 1
等 级:新手上路
帖 子:44
专家分:0
注 册:2006-4-20
得分:0 

#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.

[此贴子已经被作者于2006-9-27 21:21:00编辑过]

2006-09-27 21:07



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-93305-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.141772 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved