C++ Primer Plus笔记: 2023.06.22

下面的这段代码:

#include 
using namespace std ;

int main()
{
	cout << "What year was your house built?\n" ;
	int year ;
	cin >> year ;
	cout << "What is its street 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 built?
1966
What is its street address?
Year built: 1966
Address: 
Done!

用户根本没有输入地址的机会,当cin读取年份,将回车键生成的换行符留在输入队列之中。后面的cin.getline( )看到换行符后,将认为是一个空行,并将一个空字符串赋给address数组。

解决的方法,就是要在第一个cin的输入上下手:
方法一:

cin >> year ;
cin.get() ;		// or cin.get(ch) ;

方法二:

(cin >> year).get()		// or (cin >> year).get(ch) ;

你可能感兴趣的:(C++,Primer,Plus,c++)