-
getline (cin,name)
Hi I am trying to use getline in order to read a name and surname and sore them in 1 variable.
The program is going over getline like it does not exist.What is the reason for this?
/ / Code:
void Vstore::addemployee(string name)
{float amount;
string date;
empsal[name].name=name;
cout<<"Salary? :";
cin>>amount;
empsal[name].sal=amount;
cout<<"Date "<<name<<" joined us? :"<<endl;
cin>>date;
empsal[name].dateJoined=date;
}
in main() I have
break;
case 4:
Vtown.calcprofit();
break;
case 5:
cout<<"Name? :";
getline(cin,name);
Vtown.addemployee(name);
This is what happens when I run the program:
hello
What would you like to do
1 Get an Employees Details
2 Add an amount to income
3 Add an amount to expenses
4 See current profit
5 Add an employee
5
Name? :Salary? :
It should display name,read a value into it and then display salary?
Thanks
-
Add this line right after the call to getline():
Code:
cout << "name = \"" << name << "\"" << endl;
The problem is possibly that you're doing something bad with cin so that the buffer has something inside of it when you call getline(). The above line will tell you what was picked up.
Be careful with how you're messing with input streams. I suppose a quick fix would be to add another getline(), but you should really identify exactly what is going wrong before you try to fix it.
-
Code:
getline(cin,name);
cout << "name = \"" << name << "\"" << endl;
gives me:
What would you like to do
1 Get an Employees Details
2 Add an amount to income
3 Add an amount to expenses
4 See current profit
5 Add an employee
5
Name? :name = ""
Salary? :
-
I'm guessing you have a '\n' lying in the buffer before you call getline(). You need to clear the newline char. As I said in my last post, you can just issue another call to getline() to get around the problem, or perhaps more appropriately, you should use the C++ equivalent to a getchar().
What input operation are you doing beforehand btw?
-
> cin>>date;
This leaves a newline
> getline(cin,name);
This stops reading after a newline.
Which if it immediately follows the other variety looks like it does 'nothing'.
Always use getline() to read a whole line into a std::string.
Then use a string stream say to extract the information you require.
See scanf() vs. fgets() + sscanf() in C.
-
Thanks for the help.The problem has been soved.
-
The other option is to use std::getline(std::cin >> std::ws, name); What this gets is a single line, not including terminator '\n', where the terminator is consumed, with no leading whitespace. This is usually what you want. The only problem with this is when you might want a blank line to return a null string or an error, this silently skips blank lines.
-
I prefer to just always add cin.ignore() to ignore the newline (or other trailing whitespace) after calls to operator>>.
Or something like this:
http://cboard.cprogramming.com/showp...4&postcount=11