// 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的最后一个元素)