gets() only taking input once in while loop

Gitarooman picture Gitarooman · Jan 22, 2013 · Viewed 8.2k times · Source

I am new to C and working through some exercises, but having trouble with gets() in a while loop. In searching, I believe that it may have something to do with the \n character, but I was hoping that someone would be able to give me a more thorough explanation of what is going on here:

This loop will only run once - it will print the 'Enter last name' to screen a second time and then drop out of the loop before gets() has a chance to take any input a second time:

while (employee_num <= 10)
{
    printf("Enter last name ");
    gets(employee[employee_num].last_name);
    if(strlen(employee[employee_num].last_name) == 0)
        break;
    printf("Enter first name ");
    gets(employee[employee_num].first_name);
    printf("Enter title ");
    gets(employee[employee_num].title);
    printf("Enter salary ");
    scanf("%d", &employee[employee_num].salary);        
    ++employee_num;
}

Thanks in advance!

Answer

jman picture jman · Jan 22, 2013

You'd have a newline character (\n) in the input buffer after reading the salary. That is being picked up as the last name in the second iteration. You can ignore that by adding a getchar() after your last scanf:

while (employee_num <= 10) {
    ...
    printf("Enter salary ");
    scanf("%d", &employee[employee_num].salary);        
    ++employee_num;
    getchar();
}