cin.get和cin.getline在读取一整行时的区别
2014-08-22 12:42
295 查看
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.get()以后再调用一次cin.get()把'/n'符给读取了,可以组合式地写为cin.get(name,SIZE).get();。
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()对地址的读取。
#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.get()以后再调用一次cin.get()把'/n'符给读取了,可以组合式地写为cin.get(name,SIZE).get();。
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()对地址的读取。
相关文章推荐
- 浅谈cin>>与cin.getline读取缓冲区中的‘\n’和空格的区别
- cin,cin.get()和cin.getline()的区别
- cin.get和cin.getline的区别?
- C++ 读书笔记之 getline与cin.getline的区别
- C++中cin,cin.get()和cin.getline()的区别
- cin.get( )与cin.getline( )的区别
- C++ 输入函数 cin>>、cin.getline()和cin.get()区别
- 字符串输入函数cin.getline()、与cin.get()的区别
- C++读取键盘输入(cin/cin.getline()/cin.get()/cin.clear())
- C++ 读取键盘输入(cin/cin.getline()/cin.get()/cin.clear())
- getline和cin.getline的区别!
- cin cin.get cin.getline有什么区别?(转载加部分原创)
- cin.get和cin.getline的区别?
- cin<<,cin.get(),cin.getline()等区别与联系
- cin.get()和cin.getline()区别
- cin.get()与cin.getline()的区别
- VC问题:cin.get和cin.getline的区别?
- getline和cin.getline的区别
- cin.get( )与cin.getline( )的区别
- cin.getline()和cin.get() 的区别