char数组利用cstring中的函数strncpy,strcat,strncat合并字符串并保存显示

// practice4-3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <cstring>
const int size = 20;

int _tmain(int argc, _TCHAR* argv[])
{
	using namespace std;
	char firstName[size];
	char lastName[size];
	char fullName[2*size+1];
	
	cout<<"Enter your first name:";
	cin>>firstName;
	cout<<"Enter your last name:";
	cin>>lastName;
	strncpy(fullName,lastName,size);
	strcat(fullName,",");
	strncat(fullName,firstName,size);
	fullName[size-1]='\0';
	cout<<"Here 's the information in a single string:"<<fullName<<endl;
	system("pause");
	return 0;
}




strcat(str1,str2)会先去掉str1的结束符后再把str2接连到str1末尾,这样很符合一个字符串只能有一个结束符的规定。
 

strncpy()函数

原型:extern char *strncpy(char *dest, char *src, int n);   
用法:#include <string.h>   
功能:把src所指由NULL结束的字符串的前n个字节复制到dest所指的数组中。   
说明:如果src的前n个字节不含NULL字符,则结果不会以NULL字符结束。       
如果src的长度小于n个字节,则以NULL填充dest直到复制完n个字节。       
src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。       
返回指向dest的指针(该指向dest的最后一个元素)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值