Why does this program run fine?
#include<iostream>
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>>address;
cout << "Year built: " << year << endl;
cout << "Address: " << address << endl;
cout << "Done!\n";
return 0;
}
And why does this program not give the chance to enter the address?
#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;
}
cin>>leaves the newline character (\n) in the iostream. Ifgetlineis used aftercin>>, thegetlinesees this newline character as leading whitespace, thinks it is finished and stops reading any further.Two ways to solve the problem:
Avoid putting
getlineaftercin >>OR
Consume the trailing newline character from the cin>> before calling getline, by “grabbing” it and putting it into a “dummy” variable.
Why does the first program work & Second doesn’t?
First Program:
The
cinstatement uses the entered year and leaves the\nin the stream as garbage. Thecinstatement does NOT read (or “grab”)\n. Thecinignores\nwhen reading data. Socinin program 1 can read the data properly.Second Program:
The
getline, reads and grabs\n. So, when it sees the \n left out fromcin, it grabs the\nand thinks it is finished reading, resulting in second program not working as you expected.