質問

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!

役に立ちましたか?

解決

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();
}

他のヒント

Referring to answer by skjaidev,

With gets(), The newline character(\n), if found, is not copied into string and this is the reason for your problem.

Also, Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows).

It is considered to be a bad practise to use gets() in a program

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top