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。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .

上一篇:局部变量和成员变量的区别


下一篇:linux系统中paste命令实现列转行