Gets () only takes one input during a loop

I'm new to C and working on some exercises but having problems with gets () in a while loop. While searching, I believe it might have something to do with \ n the character, but I was hoping someone could give me a more detailed explanation of what's going on here:

This loop will only run once - it will print "Enter last name" for the second screen and then exit the loop before get () can repeat any second input:

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!

+3


source to share


2 answers


After reading the salary, you will have a newline character ( \n

) in the input buffer. This is matched as the last last name on the second iteration. You can ignore this by adding f getchar()

after the last scan:



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

      

+4


source


Referring to skjaidev's answer,

With gets()

the newline ( \n

) character , if found, is not copied to the string and that is the cause of your problem.



Also, note that get is very different from fgets

: not only gets used stdin

as a source, but does not contain the trailing character newline

in the resulting string, and does not allow you to specify a maximum size for str (which can result in a buffer overflow).

This is considered bad practice gets()

in a program

+2


source







All Articles