为什么 scanf 不适用于使用指针和 malloc 的 C 程序中的整数变量?[复制]

Why does scanf not work for the integer variables in my C program using pointers and malloc? [duplicate]

提问人:Gostodexadrez 提问时间:5/31/2023 更新时间:5/31/2023 访问量:30

问:

使用指针和 malloc 扫描结构的一部分时出现问题

#include <stdio.h>
#include <stdlib.h>
struct evento{
    char nome [100];
    char local [100];
    int dia;
    int mos;
    int anos;
};
int main (){
    int i,n;
    i=0;
    scanf ("%d",&n);
    struct evento *agenda;
    agenda =(struct evento*) malloc(n*sizeof(struct evento));
    for (i=0;i<n;i++){
        fgets (agenda[i].nome,100,stdin);
        fgets (agenda[i].local,100,stdin);
        scanf ("%d",&agenda[i].dia);
        scanf ("%d",&agenda[i].mos);
        scanf ("%d",&agenda[i].anos);
    }
    printf ("happy day");
    free(agenda);
    return 0;
}

当我输入 n 和两个字符串的值时,程序将打印引号,而不是让我输入 dia、mos 或 anos 的值。

因此,如果我输入类似 1(n 的值)、名称和事件之类的内容,程序将完成并打印引号,而不是让我输入其他值。为什么???

c 指针 struct malloc scanf

评论

0赞 Lundin 5/31/2023
混合使用 scanf 和 fgets 时,您需要注意换行符。fgets 读取换行符,但将其与数据放在一起。但是,scanf 将换行符保留在 stdin 中。所以在第一个循环中,如果你输入“hello”,输入“world”,输入“1”,输入“2”,输入“3”,输入。然后你会读到 , “”,但下一圈的循环会有来自 scanf 的尾随换行符。您需要 1) 将 fgets 读取的换行符丢弃到字符串中,以及 2) 确保删除 scanf 留下的 lf 字符 - 例如,在每个字符后添加一个空的 getchar()。"hello\n"world\n"123
0赞 Lundin 5/31/2023
正如你所知道的,stdio.h 是一个非常奇怪、有缺陷和繁琐的库。事实上,它几乎可以肯定是有史以来为任何编程语言编写的最糟糕的库,所有类别。所以我不会花很多精力来学习它,因为它现在没有用于专业的生产代码。

答: 暂无答案