gpt4 book ai didi

c - 结构和 malloc 代码得到奇怪的输出

转载 作者:太空宇宙 更新时间:2023-11-04 02:07:31 25 4
gpt4 key购买 nike

又是我,正在进步...我想感谢所有对我的上一个问题发表评论的人,这非常有帮助。到目前为止我得到了这个编译但是有一些我无法解决的奇怪的错误。

void addRecord(){//carries users input data

numRecs++;//increments numRecs by 1

struct record library; //this will hold info for user input

printf ("Please enter your first name:\n");
fgets(library.fName, sizeof(library.fName), stdin);
printf ("Please enter your last name:\n");
fgets(library.lName, sizeof(library.lName), stdin);
printf ("Please enter your hometown:\n");
fgets(library.hometown, sizeof(library.hometown), stdin);


printf("You entered %s for your first name.\n", library.fName);
printf("You entered %s for your last name.\n", library.lName);
printf("You entered %s for your hometown.\n", library.hometown);


struct record *myNewRecord;//creates a new struct pointer to store all the old data and new data


myNewRecord = malloc(numRecs * sizeof(struct record)); //allocates space to fit all old data plus the new struct data
if (myNewRecord == NULL)
{
fprintf(stderr,"Out of memory\n");
}

*myNewRecord = library;

fprintf(stderr, "You made it here!!\n");

这些是我从终端获得的结果。看起来源代码中的语法都是正确的,但问题是它出于某种原因跳过了名字 fgets。此外,当它打印出来时,它会以某种方式执行返回。你们能看出这是怎么回事吗???附言当我消除 switch case 并且在 main 中只有 addrecord() 时,它不会执行此操作。

ubuntu@ubuntu:~$ 
ubuntu@ubuntu:~$ gcc lab222.c -o lab222
ubuntu@ubuntu:~$ ./lab222

Please select from the following:
1. Print all records.
2. Print number of records.
3. Print size of database.
4. Add record.
5. Delete record.
6. Print number of accesses to database.
7. Exit.
Enter a number 1-7:4
Please enter your first name:
Please enter your last name:
Don
Please enter your hometown:
Mega
You entered
for your first name.
You entered Don
for your last name.
You entered Mega
for your hometown.
You made it here!!

最佳答案

改变:

scanf("%d",&sel);
if (scanf("%d", &sel) == 0) {
fprintf(stderr, "Error, not a valid input. Must be a number from 1 to 7.\n");
scanf("%s", &c);
continue;
}

到:

char reponse[MAX];
fgets(response, sizeof response, stdin);
int result = sscanf(response, "%d", &sel);
if (result != 1) {
fprintf(stderr, "Error, not a valid input. Must be a number from 1 to 7.\n");
continue;
}

使用 fgets() 后跟 sscanf() 解决了单独使用 scanf() 时不读取换行符的问题。您还在 if 中再次调用了 scanf(),因此它读取了两次输入。

关于c - 结构和 malloc 代码得到奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19171538/

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