Enter employee's ID : ABC
Enter hours worked per week : 40
Employee ID : ABC
Gross pay : 200
Total deduction : 51
Net pay : 149
Continue with next employee (Y/N)? : Y
Enter employee's ID : Enter hours worked per week :
The problem is.. I cannot input the employee's ID for the second time. The program directly output the "Enter hours worked per week :" together with the "Enter employee's ID : ". I can't seem to figure out the problem?
// ...
//void main()
int main() // main MUST return an int
{
char nextEmployee = 'Y';
// ...
// ( nextEmployee != 'N' || nextEmployee != 'n' ) will always be true
//while( nextEmployee != 'N' // nextEmployee != 'n' )
while( nextEmployee != 'N' && nextEmployee != 'n' )
{
cout<<"\nEnter employee's ID\t\t: ";
// there will be a new line left in the buffer after the last input
// remove it before calling getline()
cin >> ws ; // *** added
cin.getline(employeeID,40);
cout<<"Enter hours worked per week\t: ";
// ...
There are two kinds of input possible with C++ streams - formatted input and unformatted input.
The formatted input operations leave unconsumed chars (typically white spaces - new line, space, tab etc.) in the input buffer. If the next input is also a formatted input, there is no problem - by default, formatted input skips over leading white spaces. For example:
1 2 3 4 5 6
int a, b ;
std::cin >> a ; // here you type in <space>678<new-line>
// the formatted input skips over the leading space, reads 678 into 'a' and leaves a new-line in the buffer
std::cin >> b ; // here you type in 99<new-line>
// the input buffer now contains <new-line>99<new-line>, but this causes no worries
// the formatted input skips over the leading white space, reads 99 into 'b' and leaves a new-line in the buffer
Now, let us say we add an unformatted input operation to the mix, with <new-line> still in the input buffer:
1 2 3 4 5 6
char cstr[100] ;
std::cin.getline( cstr, sizeof(cstr) ) ; // here you type in 'hello world' followed by a new line.
// the input buffer now contains <new-line>hello world<new-line>
// the unformatted input operation does not skip over leading white space
// the first thing it sees is the <new-line> in the input buffer, and it returns immediately
// (after discarding the new line). hello world<new-line> still remains in the input buffer at the end of all this.
For the unformatted input to get to 'hello world', we have to remove the leading white space (new line) from the input buffer. And this is what std::cin >> std::ws does. A dumbed down explanation is here: http://www.cplusplus.com/reference/iostream/manipulators/ws/