SoThatsHow
SoThatsHow

Reputation: 366

C++ getline(), the second run of this function doesn't work

I can't figure out what's my simple IO problem:

this is the code where I do the IO:

cout << "Enter an Employee name: ";
getline(cin, empName);
cout << "Employee Position: "  ;
cin >> empPos;
cout << "Enter the Number of Years of Experience: ";
cin >> numOfExp;
cout << "Enter the deprtment Number: ";
cin >> deptNum;

and here is my wrong output: the first time that the name is read everything is fine but the second time it looks like something is automatically is passed into the name without asking the user to input anything fot the name.

Here is my output:

Name:               Unknown
Department Number:          0
Employee Position:          E
Years of Experience:        0
Salary:                     0
Total Number of Employees:  1
Enter an Employee name: arasd d
Employee Position: s
Enter the Number of Years of Experience: 12
Enter the deprtment Number: 12
Name:                       arasd d
Department Number:          12
Employee Position:          s
Years of Experience:        12
Salary:                     0
Total Number of Employees:  1
Enter an Employee name: Employee Position:

As you see the last line is the problem; any idea how to fix this?

Upvotes: 0

Views: 2797

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

The problem is probably that the last thing you read before the std::getline() is an integer (or something else using operator>>(). The formatted input operators stop reading when the first character not matching their format is encountered. For example, for an integer reading stops the monent a non-digit is entered (except for a leading sign). Thus, after reading an integer the newline character used to indicate that the input is done is still in the input buffer.

To deal with the stuck newline you can just skip any leading whitespace before calking std::getline():

if (std::getline(std::cin >> std::ws, name)) {
    ...
}

BTW, there is never a situation where you don't want to check user-input! User-input always needs checking, even in the most trivial programs where the input is assumed to be right! It help with locating the actual problems dramatically. Given your output it looks as if tve input actually didn't match what is being read...

Upvotes: 1

Related Questions