0

我正在尝试向结构内的每个字符串添加一定数量的字符,但是一些正在保存到字符串中的字符串也会附加到前一个字符串。我如何使它不附加到前一个字符串。

typedef struct {
char first[7],initial[1],last[9], street[16], city[11], state[2], zip[5], sex[1];       
int age, tenure;
float salary;
} payroll;

payroll details[15]
void readFile(payroll *details) {
int i=0;

FILE *fIn;


if (fopen_s(&fIn,"payfile.txt","r") != 0) {
    printf("Failed to open payroll.txt for reading.\n");
    return;
}

while (!feof(fIn) && i<1) {
    char buf[MAX] , age[3], tenure[2], salary[10];      

    fgets(buf,MAX,fIn);
    strsub(buf, details[i].first, 0, 6);
    printf("%s\n",details[0].first);    //gets string chars 0-6
    strsub(buf, details[i].initial, 8, 8);
    printf("%s\n",details[0].first);    //somehow initial adds to first
    strsub(buf, details[i].last, 10, 18);   //initial still gets what it was
    strsub(buf, details[i].street, 20, 21); //supposed to get until the next
    strsub(buf, details[i].city, 23, 38);   //string and read
    strsub(buf, details[i].state, 40, 41);
    strsub(buf, details[i].zip, 43, 47);
    strsub(buf, age, 49, 50);
    strsub(buf, details[i].sex, 52, 52);
    strsub(buf, tenure, 54, 54);
    strsub(buf, salary, 56, 61);

    details[i].age = atoi(age);
    details[i].tenure = atoi(tenure);
    details[i].salary = atof(salary);

    i++;
}
}

void strsub(char buf[], char sub[], int start, int end) {
int i,j;

for (j=0,i=start;i<=end;i++,j++) {
    sub[j] = buf[i];
}
sub[j] = '\0';
}
4

1 回答 1

2

您的主要问题是这些字段char first[7],initial[1],last[9],...都 1 char 太小了。 strsub(buf, details[i].first, 0, 6);从 buf 中提取 7 个字符放入first. 到目前为止,一切都很好。但是然后 strsub() 将 NUL 字节附加到 first 的第 8 个字符中,这是未定义的行为,因为 first 是 7 个字符长。您看到的 UB 是 on 的明显last串联first

将每个字段的长度增加 1。

于 2013-06-30T03:02:51.917 回答