【发布时间】:2019-04-26 11:40:54
【问题描述】:
我正在尝试创建一个结构来记录一群人。出于某种原因,每当我输入此人的房间名称时,房间名称都会替换此人的名字。这在 addResi 函数中的测试 5 中显示。
struct resi {
char *firstname;
char *lastname;
double stnscore;
char *roomName;
struct resi *next;
};
struct resi *head = NULL;
struct resi *current = NULL;
void printAll() {
struct resi *outer = head;
if (outer == NULL) {
printf("Empty\n"); fflush(stdout);
}
while (outer != NULL) {
printf("First Name: %s, Last Name: %s, Score: %lf, roomName: %s\n", outer->firstname, outer->lastname, outer->stnscore, outer->roomName); fflush(stdout);
outer = outer->next;
}
}
void addResi(char *firstname, char *lastname, double stnscore, char *roomName) {
printf("test 0\n"); fflush(stdout);
struct resi *link = (struct resi*) malloc(sizeof(struct resi));
printf("test 1 %s\n", firstname); fflush(stdout);
strcpy(link->firstname, firstname);
printf("test 2 %s\n", link->firstname); fflush(stdout);
strcpy(link->lastname, lastname);
printf("test 3\n"); fflush(stdout);
link->stnscore = stnscore;
printf("test 4\n"); fflush(stdout);
strcpy(link->roomName, roomName);
printf("test 5 %s %s\n", link->firstname, link->roomName); fflush(stdout); //they shouldn't be the same.
link->next = head;
head = link;
}
int main (void)
{
int totalStud, tempX = 0;
char firTemp[21], lasTemp[21], roomTemp[21];
double scrTemp;
printf("How many residences?\n"); fflush(stdout);
scanf("%d", &totalStud);
if (totalStud < 5) {
printf("The number %d is less than 5, please type a different number\n",
totalStud); fflush(stdout);
}
while (totalStud < 5) {
scanf("%d", &totalStud);
}
printf("type the residences with following format\nfirst name last name score room\n"); fflush(stdout);
for (tempX = 0; tempX < totalStud; tempX++) {
scanf("%20s %20s %lf %20s", firTemp, lasTemp, &scrTemp, roomTemp);
printf("test mid %s %s %lf %s\n", firTemp, lasTemp, scrTemp,
roomTemp); fflush(stdout);
addResi(firTemp, lasTemp, scrTemp, roomTemp);
printAll();
}
}
如果我输入“5”,然后输入“Bob Billy 45.5 Jackson”,最后的输出应该看起来像“First Name: Bob, Last Name: Billy, Score: 45.500000, roomName: Jackson”,但它显示为“First姓名:杰克逊,姓:比利,分数:45.500000,房间名:杰克逊”
【问题讨论】:
-
你从哪里想到要到处写
fflush(stdout)? -
如果你真的想要无缓冲的输出,最好在程序开头使用
setvbuf(stdout, NULL, _IONBF, 0);。
标签: c string memory linked-list