cin and cin.getline

Overview

关于cin与cin.getline在使用时要注意的地方,关键在于”newline”的处理。

Code

我们先来看一个例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

#include <iostream>

int main(){
using namespace std;
cout<<"What year was your house biult?\n";
int year;
cin>>year;
cout<<"What is its streer address?\n";
char address[80];
cin.getline(address, 80);
cout<< "Year built: "<<year<<endl;
cout<<"Address: "<<address<<endl;
cout<<"Done!\n";
return 0;
}

输出:

What year was your house biult?
2017
What is its streer address?
Year built: 2017
Address:
Done!

可以看到,还没输入地址,就打印并结束了程序。
原因:

The problem is that when cin reads the year, it leaves the newline generated by the Enter key in the input queue. Then, cin.getline() reads the newline as an empty line and assigns a null string to the address array.

解决办法:

The fix is to read and discard the newline before reading the address.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

int main(){
using namespace std;
cout<<"What year was your house biult?\n";
int year;

// 这里使用get将作为cin结束的newline清除即可
//(cin>>year).get();
cin>>year;
cin.get();


cout<<"What is its streer address?\n";
char address[80];
cin.getline(address, 80);
cout<< "Year built: "<<year<<endl;
cout<<"Address: "<<address<<endl;
cout<<"Done!\n";
return 0;
}

输出:

What year was your house biult?
1998
What is its streer address?
earth
Year built: 1998
Address: earth
Done!

Reference

C++ Primer Plus(5th Edition) Page147

击蒙御寇