I have written a program that stores employees in a database object. You can Add, hire, fire, promote, demote, and display employees. The program uses an interface, a database class, and an employee class with member functions.
The strange behavior is in my switch statement in interface.cpp. I have a '#' that represents a command line. Add and Display functions are ok, but if I hire, fire, promote or demote. It will display '##' for the next input. I ran the debugger and after hire/fire/promote/demote is called, the first if-statement goes to 'else' and I'm trying to figure out why.
That happens because you're mixing taking input with std::getline() and with operator>>() overloads. The overloads pop characters from the input buffer until they find whitespace (' ', '\t', '\n'), but don't pop the whitespace itself. So if you type in, say, "george\n", after getting the input with operator>>(), the input buffer will contain "\n". If after that you use std::getline() to get the input, the function will treat that trailing newline as if it had just been typed in, and will simply store an empty string into the std::string.
Luckily, you're only using operator>>() in one place, so the solution is simple:
1 2 3 4 5 6 7 8 9 10
int id;
cout << "Please enter ID Number for the employee: "
<< endl;
//cin >> id;
{
std::string templine;
std::getline(std::cin, templine);
std::stringstream tempstream(templine);
tempstream >> id;
}
Personally, I prefer to never use operator>>() with stdin. Its behavior is IMO a breach of the Principle of Least Astonishment.
Thank you helios for your reply! I will try this code today.
Honestly though, is this a sloppy solution for bad coding on my part? In other words, was there a more professional approach I should have taken initially to avoid this problem?