Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1252787
  • 博文数量: 247
  • 博客积分: 5587
  • 博客等级: 大校
  • 技术积分: 2060
  • 用 户 组: 普通用户
  • 注册时间: 2010-02-24 13:27
文章分类
文章存档

2012年(101)

2011年(44)

2010年(102)

分类: C/C++

2010-09-05 09:40:06

cin.getline()和cin.get()都是对输入的面向行的读取,即一次读取整行而不是单个数字或字符,但是二者有一定的区别。 
cin.get()每次读取一整行并把由Enter键生成的换行符留在输入队列中,比如: 

#include  
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.get()以后再调用一次cin.get()把'\n'符给读取了,可以组合式地写为cin.get(name,SIZE).get();。 


cin.getline()每次读取一整行并把由Enter键生成的换行符抛弃,如: 

#include  
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()对地址的读取。
阅读(1501) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~