C++中cin的常用用法

code:

// File name:           Cin_Usage
// Last modified Date:  2021年10月13日21点26分
// Last Version:        V1.0
// Descriptions:        本程序包含cin的常用用法
#include <iostream>
using namespace std;//将命名空间std的所有名字都引用了

int main()
{
	char test[30];
	/*1 cin测试*/
	cout << "1 cin测试:" << endl;
	cout << "输入字符串(字符串1+空格+字符串2):" << endl;
	cin >> test;
	cout << "test = "<<test << endl;//可以观察到的是,cin是不读取空格的,空格会被略去
	cin >> test;//用于读取空格后面缓存的内容,不影响后面的输入
	cout << "吃掉缓存的字符串2 = " << test << endl << endl;
	cin.get();

	/*2 吃掉回车符cin.get()*/
	char test1[30];
	char test2[30];
	cout << "2 吃掉回车符cin.get()" << endl;
	cout << "输入字符串1:" << endl;
	cin >> test1;
	cin.get();//只有加上了这句,test2才可以正常读取,否则test2会读取为输入test1后的回车符。
	cout << "输入字符串2:" << endl;
	cin >> test2;
	cin.get();
	cout << "test1 = " << test1 << endl;
	cout << "test2 = " << test2 << endl << endl;

	/*3 读取字符cin.get(ch)*/
	char ch;
	cout << "3 读取字符cin.get(ch)" << endl;
	cout << "输入单个字符:" << endl;
	cin.get(ch);//可以观察到就算是输入空格也会被读取
	cin.get();
	cout.put(ch);
	cout << endl << endl;

	/*4 cin面向行的输入*/
	/*方法1 cin.getline()*/
	cout << "4 方法1 cin.getline()" << endl;
	const int ArSize = 20;
	char name[ArSize];
	char dessert[ArSize];
	char name1[ArSize];
	char dessert2[ArSize];

	cout << "getline() test" << "\n";
	cout << "Enter your name:\n";
	cin.getline(name, ArSize);//cin.getline()会主动吃掉字符串输入最后的回车符,因此不需加上get()吃掉回车符
	cout << "Enter your favorite dessert:\n";
	cin.getline(dessert, ArSize);
	cout << "I have some delicious " << dessert;
	cout << " for you, " << name << ".\n"<<endl;
	/*方法2 cin.get()*/
	cout << "4 方法2 cin.get()" << endl;
	cout << "get() test" << "\n";
	cout << "Enter your name:\n";
	cin.get(name, ArSize).get();//cin.get()不会主动吃掉字符串输入最后的回车符,因此需要加上get()吃掉回车符
	cout << "Enter your favorite dessert:\n";
	cin.get(dessert, ArSize).get();
	cout << "I have some delicious " << dessert;
	cout << " for you, " << name << ".\n";

	return 0;
}

运行结果:

1 cin测试:
输入字符串(字符串1+空格+字符串2):
Jasmine lily
test = Jasmine
吃掉缓存的字符串2 = lily

2 吃掉回车符cin.get()
输入字符串1:
lili
输入字符串2:
bobo
test1 = lili
test2 = bobo

3 读取字符cin.get(ch)
输入单个字符:
o
o

4 方法1 cin.getline()
getline() test
Enter your name:
lili
Enter your favorite dessert:
cakes
I have some delicious cakes for you, lili.

4 方法2 cin.get()
get() test
Enter your name:
bobo
Enter your favorite dessert:
cakes
I have some delicious cakes for you, bobo.

D:\Prj\C++\C++_Learning\Cin_Usage\Debug\Cin_Usage.exe (进程 10304)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jasmine-Lily

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值