C++求助,strncpy用法解释!

#include <iostream>
#include <string.h>
using namespace std;

int main()

{
int num,i=0;
cin>>num;

for(i=0; i<num; i++)
{
char id[18] ;
cin>>id;
char s[6]={};
strncpy(s,id,6);
cout<<id<<"\t"<<s<<endl;
}
return 0;

}
将id的前6个字符复制给s并输出,为什么得不到想要的东西!

第1个回答  2014-04-21
因为strncpy不自动追加空字符到字符串结尾,所以s字符串没有结尾,需要做s[6] = 0;操作才行
第2个回答  2014-04-21
如果你输入的字符串id的长度大于6个,strncpy到s时,会导致s不能正常的是\0结尾。
第3个回答  推荐于2018-04-13
char s[6]={};
改为
char s[7]={0};
试试,原因是:如果你输入的id字符串长度等于或大于6个时,前6个字符都会被
复制到s中,而s只有6个字符的空间,导致s字符串最后的字符不是终止符结束,cout的输出结果就可能会出现乱码。所以你要把s字符串预留出一个字符来保存终止符'\0'。
=========================================================
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.
=========================================================
大意是:
strncpy函数从源字符串中复制指定个数的字符到目标字符串中,并返回目标字符串,如果指定字符数小于或等于源字符串的长度,空字符不会自动添加到被复制的字符串后面。如果指定字符数大于源字符串的长度,目标字符串将被空字符补足到指定的长度。如果源字符串和目标字符串存在叠加的情况(即两个字符串都是同字符串的一部分,且有部分内容首尾重合),则strncpy的运行结果是不确定的。本回答被提问者和网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网