I am having another problem.
When I prompt for input before using a getline(cin,name); The second never prompts for input. (sorry, i don't know how to explain it)
//test
#include<iostream>
#include<string>
usingnamespace std;
int main()
{
int year;
string name;
cout<<"enter year of birth ";
cin>>year;
cout<<"Enter name ";
getline(cin,name);
cout<<"You are "<<name<<" and were born in the year "<<year<<endl;
return 0;
}
Any ideas?
It works if I move the year after the name, but not before!?
The reason why it is not asking you for an input is that you are mixing cin and getline statements.
Let me explain: getline() stores all the text you enter until when you enter a specific character. By default that is '\n', the new line character (i.e. when you press enter).
You can change this by adding one more parameter to getline()
example:
getline(cin, name, 'a');
This getline will store every letter you enter until when you enter an a.
So, getting back to your problem, when you enter the value of year using cin, you enter a number and then you press enter (which corresponds to the new-line character '\n'). This character gets goes into the getline() function, and since your getline is set to stop accepting values when it sees a \n the function getline() ends and your program goes on to the next instruction.
An easy way to avoid this you can use the ignore() function before you use getline.
For example ignore(1000, '\n'); is going to ignore up to 1000 characters until when it sees a \n, which will be the last character ignored.
#include <iostream>
#include <string>
#include <sstream> // for stringstreams
usingnamespace std;
int main()
{
int year;
string name;
string line;
stringstream stream;
cout<<"enter year of birth ";
getline(cin, line);
stream << line;
stream >> year;
cout<<"Enter name ";
getline(cin,name);
cout<<"You are "<<name<<" and were born in the year "<<year<<endl;
return 0;
}