Hi, I am learning about get() and getline() in c++. The book I was following had an example that I didn't quite understand. Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
// numstr.cpp -- following number input with line input
#include <iostream>
int main()
{
using namespace std;
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;
}
|
Then it gives the following explanation:
You never get the opportunity to enter the address. 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.
What I don't understand is why would the compiler accept the 'Enter key' pressed after the year input (cin >> year), as the address, even before declaring the address array?
Also, I realise that get(), getline(), or get(ch) solves the problem. I have another doubt, do we have to declare
char ch; to use get(ch); ?
Thanks in advance, I apologize for the lengthy questions.