fgets() skipped [duplicate]

2020-01-29 19:19发布

I am writing a program for school where the user inputs name, hours worked, and hourly wage.

int main ()
{
    char name[SIZE];
    char selection = 'Z';
    int hoursWorked = 0,
        counter = 0,
        flag = 1;
    float hourlyRate = 0.0;
    const float otRate = 1.5;
    const int week = 40;

    while (flag == 1)
    {
        system ("cls");
        printf ("\n\tP A Y R O L L  P R O G R A M\n");
        printf ("---------------------------------------------\n");
        printf ("\t(A) - New Payroll Info\n\t(B) - Display Payroll\n\t(C) - Quit\n\t");
        scanf (" %c", &selection);
        selection = toupper (selection);
        switch (selection)
        {
        case 'A':
            system ("cls");
            printf ("Enter Employee Name: ");
            fgets ( name, SIZE, stdin );
            strip_newline( name, 50 );
            printf ("\nEnter Hourly Rate: ");
            scanf ("%f", &hourlyRate);
            printf ("\nEnter Hours Worked This Week: ");
            scanf ("%d", &hoursWorked);
            system ("pause");
            break;

SIZE is 50, stdio.h & stdlib.h are included. When I compile and move to the A switch it skips the fgets() input and goes straight to the "Enter Hourly Rate: " scanf(). I have tried changing the order putting the scanf()s in front of the fgets(), to no avail.

标签: c scanf
2条回答
Explosion°爆炸
2楼-- · 2020-01-29 19:28

scanf probably isn't eating the return at the end of the line, so it's being passed to the first fgets. Personally, I hate scanf - it's better to use fgets and then parse the line using sscanf.

查看更多
狗以群分
3楼-- · 2020-01-29 19:37

Your scanf call left a newline character in the input buffer. Consequently, when the fgets call is made, it reads that newline and returns.

As per pmg's comment above, check out the answer to Question 12.18a in the C FAQ.

查看更多
登录 后发表回答