cin.get( ) VS cin.getline( )

cin.get()有两种形式:cin.get(char str[], int size)读取整行,cin.get()读取单个字符。

1.cin.get(char str[], int size)

cin.getline()和cin.get()都是对输入的面向行的读取,即一次读取整行而不是单个数字或字符,但是二者有一定的区别。

cin.get()每次读取一整行并把由Enter键生成的换行符留在输入队列中,比如:
#include <iostream>
using std::cin;
using std::cout;
const int SIZE = 15;
int main( ){
	cout << "Enter your name:";
	char name[SIZE];
	cin.get(name,SIZE);
	cout << "name:" << name;
	cout << "\nEnter your address:";
	char address[SIZE];
	cin.get(address,SIZE);
	cout << "address:" << address;
}
输出:
Enter your name:jimmyi shi
name:jimmyi shi
Enter your address:address:

在这个例子中,cin.get()将输入的名字读取到了name中,并将由Enter生成的换行符'\n'留在了输入队列(即输入缓冲区)中,因此下一次的cin.get()便在缓冲区中发现了'\n'并把它读取了,最后造成第二次的无法对地址的输入并读取。


cin.getline()每次读取一整行并把由Enter键生成的换行符抛弃,如:
#include <iostream>
using std::cin;
using std::cout;
const int SIZE = 15;
int main( ){
	cout << "Enter your name:";
	char name[SIZE];
	cin.getline(name,SIZE);
	cout << "name:" << name;
	cout << "/nEnter your address:";
	char address[SIZE];
	cin.get(address,SIZE);
	cout << "address:" << address;
}
输出:
Enter your name:jimmyi shi
name:jimmyi shi
Enter your address:YN QJ
address:YN QJ

由于由Enter生成的换行符被抛弃了,所以不会影响下一次cin.get()对地址的读取。

2.cin.get()

cin.get()读取单个字符时也会把由Enter键生成的换行符留在输入队列中,可由下面程序看出:

#include <iostream>
using std::cin;

int main()
{
	cin.get();
	cin.get();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值