C++Primer Plus第四章结构编程练习3

3.编写一个程序,它要求用户首先输入其名,然后输入其姓;然后程序使用一个逗号和空格将姓和名组合起来,并存储和显示组合结果。请使用char数组和头文件cstring中的函数。下面是该程序运行时的情形:

Enter your first name:Flip

Enter your last name:Fleming

Here's the information in a single string: Fleming, Flip

cpp 复制代码
#pragma region 第四章练习3
/*
3.编写一个程序,它要求用户首先输入其名,然后输入其姓;
然后程序使用一个逗号和空格将姓和名组合起来,并存储和显示组合结果。
请使用char数组和头文件cstring中的函数。下面是该程序运行时的情形:
Enter your first name:Flip
Enter your last name:Fleming
Here's the information in a single string: Fleming, Flip
*/
#if 1
#include <iostream>
#include <cstring>
#include <string>

int main()
{
	using namespace std;
	char firstName[20];
	char lastName[20];
	cout << "Enter your first name : ";
	cin.getline(firstName, 20);
	cout << "Enter your last name : ";
	cin.getline(lastName, 20);
	//存储
	char name[40] ;
	int len1 = strlen(lastName) + 1;
	strcpy_s(name, len1, lastName);//原函数strcpy要报错,这里改用更安全的strcpy,下面的strcat_s同理
	int len2 = strlen(name) + strlen(", ") + 1;
	strcat_s(name, len2, ", ");
	int len3 = strlen(name) + strlen(firstName) + 1;
	strcat_s(name, strlen(firstName)+strlen(name) + 1, firstName);
	//显示
	cout << "Here's the information in a single string: " << name << endl;
	return 0;
}
#endif 
#pragma endregion

这里要注意的点:求字符串长度不能用sizeoof(),而是使用strlen()函数求字符串的长度,这里是不一样的,需要注意

相关推荐
saltymilk1 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥1 天前
C++ lambda 匿名函数
c++
沐怡旸1 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥1 天前
C++ 内存管理
c++
博笙困了2 天前
AcWing学习——双指针算法
c++·算法
感哥2 天前
C++ 指针和引用
c++
感哥2 天前
C++ 多态
c++
沐怡旸2 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4163 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥3 天前
C++ std::set
c++