-
Missing an input
In the following function it works fine the first time through the loop but on the second pass instead of outputting "Employees name : " and waiting for the input it outputs "Employees name : Payrate : " and waits for that output.
Why is it skipping the name input please?
Code:
int GetInfo()
{
char name[256];
float rate;
float hours;
for (int x(0); x<6; x++)
{
cout<<"Employees name : ";
cin.getline (name,256);
//employee.at[x]=name;
cout<<"Payrate : ";
cin>>rate;
//payrate.at[x]=rate;
cout<<"Hours worked : ";
cin>>hours;
//hoursworked.at[x]=hours;
//totalpay.at[x]=rate * hours;
cout<<"Employee : "<<name<<"\n";
cout<<"Payrate : "<<rate<<"\n";
cout<<"Hours : "<<hours<<"\n";
}
-
istream::ignore - C++ Reference
Between >> and getline calls, you need to "flush" the input stream up to the next newline.
Mixing input methods is always a hit and miss affair.
Ideally, you should just use getline() to read to some buffer, then extract what you need from the buffer.
-
Salem has explained what to do, here is the "why this is happening" part:
At the end of the first time through the loop you ask the user for the "hours worked". You enter a value and press the enter key. The cin>> statement extracts and stores the numeric value but leaves the newline character in the input stream. This leftover data causes the problem when you start the loop body over again. The getline statement sees the newline character and extracts it (effectively acting as if the user simply pressed enter at this point without entering a name) before continuing on with the rest of the code by asking for the pay rate. This has the effect of the program skipping allowing the user to enter data for the employee's name for the second and subsequent loop iterations (the first loop iteration is fine).
As hinted by Salem this is due a difference in how input is handled between cin>> and getline and why Salem mentioned the caveat about mixing such input statements. This is a very common problem for beginners to trip themselves up on.
-
I have found that if I use cin.ignore(); after the cin>>hours; that works OK; however if I use it before cin.getline (name,256); I lose the first character of the name but only on the first pass through the loop; it works OK for the second and subsequent passes.