从字符串加载结构

时间:2017-05-07 03:16:58

标签: c file pointers struct

我有一个字符串格式如下:

Surname(7characters) Name(7characters) ID(8characters) Salary(5characters)

我想将它加载到struct employee:

typedef struct{
    char surName[20];
    char name[20];
    long int id;
    int salary;
}employee;

void loadEmployee(employee *empl,char line[]){
    char *aux=line+strlen(line);
    *aux='\0';
    aux-=6;
    sscanf(aux+1,"%d",&empl->salary);

    *aux='\0';
    aux-=9;
    sscanf(aux+1,"%ld",&empl->id);

    *aux='\0';
    aux-=8;
    sscanf(aux+1,"%s",empl->name); //!!!!ERROR

    *aux='\0';
    sscanf(line,"%s",empl->surname);//!!!!ERROR
}

int main(){
    employee empl;
    loadEmployee(&empl,"Friedman John     37243365 50000");
    return 0;
}

错误表示char格式指针arg。我做错了什么?

1 个答案:

答案 0 :(得分:0)

继续发表评论,您可以通过解析,大大简化您的loadEmployee功能(并通过提供有意义的返回类型,可以检查其成功/失败来改进您的验证)单个调用中的字符串,并在失败时返回NULL的指针,例如

#include <stdio.h>

typedef struct {
    char surname[20];
    char name[20];
    long int id;
    int salary;
} employee;

employee *loadEmployee (employee *empl, char *line)
{
    if (sscanf (line, "%19s %19s %ld %d", 
        empl->surname, empl->name, &(empl->id), &(empl->salary)) == 4)
        return empl;

    return NULL;
}

int main (void) {

    employee empl;

    if (loadEmployee (&empl, "Friedman Jhon     37243365 50000"))
        printf ("empl.name: %s\nempl.surname: %s\n"
                "empl.id: %ld\nempl.salary: %d\n",
                empl.name, empl.surname, empl.id, empl.salary);

    return 0;
}

示例使用/输出

$ ./bin/stringstruct
empl.name: Jhon
empl.surname: Friedman
empl.id: 37243365
empl.salary: 50000