gpt4 book ai didi

c - 在 C 中取出一段字符数组的问题

转载 作者:太空宇宙 更新时间:2023-11-04 03:19:36 26 4
gpt4 key购买 nike

我这里有一个 source.txt 文件: https://palomar.blackboard.com/bbcswebdav/pid-1168887-dt-content-rid-3710280_1/courses/2177-70219/payfile%281%29.txt

void readData() { // Scans each line from the .txt and puts each line into an element in the array
FILE *fp;
fp = fopen("info.txt", "r");

char Line[100];
int i = 0;

while (!feof(fp)) {

char agetemp[3];
char tenuretemp[2];
char salarytemp[7];

fgets(Line, 100, fp);
strsub(Line, employee[i].first, 0, 6);
strsub(Line, employee[i].initial, 8, 9);
strsub(Line, employee[i].last, 10, 18);
strsub(Line, employee[i].street, 20, 35);
strsub(Line, employee[i].city, 37, 46);
strsub(Line, employee[i].state, 49, 50);
strsub(Line, employee[i].zip, 52, 56);
strsub(Line, employee[i].sex, 61, 61);

strsub(Line, agetemp, 58, 59);
employee[i].age = atoi(agetemp); // converted the age column to an int

strsub(Line, tenuretemp, 63, 63);
employee[i].tenure = atoi(tenuretemp); // converted tenure column to an int

strsub(Line, salarytemp, 65, 70);
employee[i].salary = atof(salarytemp); // converted the salary column to float

i++;
}
}

我的任务是给我一个名为 strsub 的用户自定义函数,它在此处定义:

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

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

基本上,当我扫描源 .txt 文件时,strsub 函数会挑选出特定的片段并将它们放入相应的结构数组中。它在大多数情况下工作正常,例如当我打印出 employee[2].city 时:

https://prnt.sc/hl25n7

那里没有错。然而,当我尝试打印出 employee[i].first 变量时,它把一堆字母聚集在一起,比我告诉它的要多,我不知道为什么。这是我尝试打印 employee[2].first 时的图片:

https://prnt.sc/hl26gt

readData() 中,我只告诉它从 0 到 6,为什么它接收的输入比我告诉它的要多,而不仅仅是前 7 个字符?

哦,这就是我的结构;我把它放在一个单独的头文件中:

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

最佳答案

我们需要查看员工的记录结构。如果 first 被定义为 char[7] 那么它没有足够的内存来容纳 0-6(即 7 个​​字符)+ 空终止。此外,如果初始值为 1 个字符,如果输入为 8、9,您的函数将处理 2 个字符。

关于c - 在 C 中取出一段字符数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com