Why can't I get the stdin data from using fgets?



  • #include <stdio.h>
    #include <string.h>
    #include "end.h"
    
    #define MAX_LENGTH 21
    
    struct Employee {
        char lastName[MAX_LENGTH];
        char firstName[MAX_LENGTH];
        char title[MAX_LENGTH];
        int salary;
    };
    
    int main() {
        int i, j, number;
        printf("%s", "Enter the number of employees: "); fflush(stdout);
        scanf("%d", &number);
        struct Employee employee[number];
    
        for (i = 0; i < number; ++i)
        {
            printf("Enter the last name: "); fflush(stdout);
            fgets(employee[i].lastName, sizeof(employee[i].lastName), stdin);
            if (strlen(employee[i].lastName) == 0)
                break;
            printf("Enter the first name: "); fflush(stdout);
            scanf("%20s", employee[i].firstName);
            printf("Enter the title: "); fflush(stdout);
            scanf("%20s", employee[i].title);
            printf("Enter the salary: "); fflush(stdout);
            scanf("%d", &employee[i].salary);
            if (i < number-1)
                printf("%s\n", "The next one!");
        }
    
        for (j = 0; j < number; ++j)
        {
            printf("{%s,%s,%s,%d}\n", 
                employee[j].lastName, 
                employee[j].firstName, 
                employee[j].title, 
                employee[j].salary);
        } 
        separate();
        return 0;
    }
    

    https://i.stack.imgur.com/dylfr.png



  • In these proposals

    scanf("%d", &number);
    

    and

    scanf("%d", &employee[i].salary);
    

    function scanf Read the symbols to the divider, which in particular is the symbol of the new line that remains in the intake buffer. Therefore, when the cycle is used again, fgetsit reads all the symbols to the symbol of the new line, including the symbol of the new line itself. That is to say, only this symbol of the new line (and possibly the gaps in front of this symbol, if the user introduced them after the introduction of the chips), which remained in the introduction buffer after the above proposals.

    You need to remove it from the intake buffer.

    It would be easier to read all the data using the function fgets For numerical data, you could use a function. atoi to the line read.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2