【问题标题】:Why is this program that should take 11 input end after only taking a single input? [duplicate]为什么这个应该输入11个输入的程序只输入一个输入就结束了? [复制]
【发布时间】:2021-07-21 07:17:16
【问题描述】:

代码如下:

#include <stdio.h>

int main()
{
    struct date
    {
        int year;
        int month;
        int day;
    };
    struct address
    {
        char city[15];
        char district[15];
    };
    struct student
    {
        char name[25];
        int roll_no;
        struct date DOB;
        struct address add;
    };
    struct student BIM[10];
    int i;
    for(i=0;i<11;i++)
    {
        printf("Enter student name: ");
        scanf("%s",BIM[i].name);
        printf("Enter roll no: ");
        scanf("%d",&BIM[i].roll_no);
        printf("Enter Date of birth: ");
        scanf("%d %d %d",BIM[i].DOB.year,BIM[i].DOB.month,BIM[i].DOB.day);
        printf("Enter address: ");
        scanf("%s %s",BIM[i].add.district,BIM[i].add.city);
    }
    int roll;
    printf("Enter roll no: ");
    scanf("%d",&roll);
    for(i=0;i<11;i++)
    {
        if(roll==BIM[i].roll_no)
        {
            printf("Name : %s",BIM[i].name);
            printf("Roll no : %d",BIM[i].roll_no);
            printf("DOB : %d/%d/%d",BIM[i].DOB.year,BIM[i].DOB.month,BIM[i].DOB.day);
            printf("Address : %s,%s",BIM[i].add.district,BIM[i].add.city);
            break;
        }
    }
}

程序在第一次循环中取 DOB 后结束。

以下是警告:

main.c:32:17: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
         scanf("%d %d %d",BIM[i].DOB.year,BIM[i].DOB.month,BIM[i].DOB.day);


main.c:32:20: warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘int’ [-Wformat=]
         scanf("%d %d %d",BIM[i].DOB.year,BIM[i].DOB.month,BIM[i].DOB.day);


main.c:32:23: warning: format ‘%d’ expects argument of type ‘int *’, but argument 4 has type ‘int’ [-Wformat=]
         scanf("%d %d %d",BIM[i].DOB.year,BIM[i].DOB.month,BIM[i].DOB.day);

【问题讨论】:

  • 您是在问如何修复警告或为什么程序不等待更多输入?
  • 警告告诉您,您向scanf 提供了错误的参数。如果在预期地址时传递整数,则会导致未定义的行为,这可能会导致崩溃。此外,您应该始终检查任何 I/O 函数的返回值,例如 scanf
  • 您有一个 10 个元素的数组,并且想要在该数组中使用 11 个元素?这没有任何意义。
  • 至于程序退出的原因,不使用printf的正确参数类型会调用未定义的行为,在这种情况下会导致程序崩溃。

标签: c


【解决方案1】:

您在那里缺少&amp;

【讨论】:

  • 这对于一个好的答案来说有点短。你可以多解释一下。它也只解决警告,而不是问题本身。
【解决方案2】:

我认为您应该在对不是指针或数组的变量使用 scanf 时使用 &amp; 字符,因为 scanf 需要您用来存储输入数据的变量的内存位置,或者您尝试填充的数组的第一个内存位置(您可以通过简单地使用不带索引的名称来寻址数组来获得)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多