fgets from stdin problems [C]

后端 未结 3 483
清歌不尽
清歌不尽 2021-01-07 01:08

I\'m writing a program that works with files. I need to be able to input data as structures, and eventually read it out. The problem i have at the moment is with this code:<

3条回答
  •  礼貌的吻别
    2021-01-07 01:58

    I tried your code and can't reproduce the problem. The following code works just the way you would expect, it prompts for the name, wait for you to type the name, then prompts for the address, etc.

    I'm wondering if you don't need to read stdin and empty it before you prompt for more input?

    typedef struct {
        char* name;
        char* address;
    }employeeRecord;
    
    int readrecord(employeeRecord &record)
    {
       char name[50];
       char address[100];
    
       printf("\nenter the name:");
       fgets(name, sizeof(name), stdin);
       record.nameLength = strlen(name) + 1;
       record.name = malloc(sizeof(char)*record.nameLength);
       strcpy(record.name,name);
    
       printf("\nenter the address:");
       fgets(address, sizeof(address), stdin);
    
       ...    
    }
    

    Incidently, you want to add 1 to strlen(name), not subtract 1. or, if you want name stored in your record without a terminating null, then you need to use memcpy to copy the string into your record, not strcpy.

    Edit:

    I see from comments that you are using scanf to read the choice value, this is leaving a \n in the input buffer which is then picked up by your first fgets call. What you should do instead is to use fgets to read in the choice line, and then sscanf to parse the value out of the input. like this

    int choice;
    char temp[50];
    fgets(temp, sizeof(temp), stdin);
    sscanf(temp, "%d", &choice);
    

    that should make the whole issue of flushing stdin moot.

提交回复
热议问题