第四章 复合类型

1.只要显式的将第一个元素初始化为0,其余的编译器会自动初始化为0。
在数组中使用字符串

#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;

int main()
{
   
	using namespace std;
	const int size = 15;
	char name1[size];
	char name2[size] = "c++owboy";//直接定义字符串常量
	cout << "howdy!I'm " << name2;
	cout << "! What's your name?\n";
	cin >> name1;
	cout << "well, " << name1 << ",your name has ";
	cout << "strlen(name1)" << "letters and is stored\n";
	cout << "in an array of " << sizeof(name1) << "bytee.\n";
	cout << "Your initial is " << name1[0] << ".\n";
	name2[3] = '\0';//将c++之后的数值直接舍去,不考虑\0后面的数值
	cout << "Here arethe first 3 characters of my name: ";
	cout << name2 << endl;
	return 0;
}

2.每次读取一行字符串输入
getline()和get();这两个函数都读取一行输入,知道到达换行符。之后getline()将丢弃换行符,而get()将换行符保留在输入序列中。

#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
 
int main()
{
   
	using namespace std;
	const int Arsize = 20;
	char name[Arsize];
	char dessert[Arsize];

	cout << "Enter your name:\n";
	cin.getline(name, Arsize);//通过换行符来确定行尾,但不保存换行符。相反,在存储字符串时,它用空字符来替换换行符。
	cout << "Enter your favorite dessert:\n";
	cin.getline(dessert, Arsize);
	cout << "I have some delicious " << dessert;
	cout << " for you," << name << ".\n";
	return 0;
}

2.1、get()

cin.get(name,Arsize);
cin.get();//读取换行符
cin.get(dessert,Arsize);
还有一种方法:
cin.get(name,Arsize).get();//相当于两次调用cin.getline();

2.2、string()

#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
using namespace std;
 
int main()
{
   
	using namespace std;
	char charr1[20];
	char charr2[20] = "jaguar";
	string str1;
	string str2 = "panther";
	cin >> charr1;
	cin >> str1;
	cout << charr1 << " " << charr2 << " ";
	cout << str1 << " "<<str2 << endl;
	cout << charr2[2] << endl;
	cout << str2[2]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值