一、简述
在头文件<cstring>
中,有两个函数strcpy()
和strcat()
。
二、详细介绍
他们各自的作用如下:
1.strcpy()
复制字符串。格式为 strcpy(char *Destination, const char *Source)
,由此可见,其接受一个 char * 参数和一个 const char * 参数。
例如:
strcpy(full_name, first_name); //将 first_name 复制给 full_name
—→ 其作用是将 first_name 数组中的字符串
复制给 full_name 数组
。值得注意的是,它不仅复制字符串内容,还会复制字符串的结束符。
***注意:目标字符串的长度一定不能小于原字符串的长度,否则会溢出。
2. strcat()
拼接字符串。格式为 strcat(char *Destination, const char *Source)
,由此可见,其接受一个 char * 参数和一个 const char * 参数。
例如:
strcat(full_name, last_name); //将 last_name 拼接在 full_name 之后
—→其作用是将 last_name 数组中的字符串
拼接在 full_name 数组中的字符串
之后。
三、题目
/*
编写一个程序,它要求用户首先输入名,然后输入姓,
接着使用一个逗号和空格将姓与名组合起来,并存储和显示组合结果。
请使用 char 数组和头文件 cstring 中的函数。
下面是该程序运行时的情形。
Enter your first name: Flip
Enter your last name: Fleming
Here's the information in a single string: Fleming, Flip
*/
四、代码
//预处理指令
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstring> //使用 strcpy()和 strcat()函数
using namespace std; //名字空间声明
const int SIZE = 20; //使用常量表示字符数组的长度
int main()
{
char first_name[SIZE];
char last_name[SIZE];
char full_name[SIZE * 2];
cout << "Enter your first name: ";
cin.getline(first_name, SIZE);
cout << "Enter your last name: ";
cin.getline(last_name, SIZE);
//通过 strcpy() 和 strcat() 函数将两个字符串复制和组合
strcpy(full_name, first_name);
strcat(full_name, ",");
strcat(full_name, " ");
strcat(full_name, last_name);
cout << "Here's the information in a single string: " << full_name << endl;
return 0;
}
五、之后会遇到的问题
会出现 C4996 的警告,解决方案如下:
关于使用vs敲代码时遇到的C4996警告的解决方案
ps:
如果本文没有帮助到大家,可以评论或私信,我会在我已有的知识基础上对其进行补充~我是一个小白,我爱编程,这些 C++ 笔记如有错误,请指出~
