我的struct c编程在达到char值时崩溃了

时间:2017-11-21 11:50:55

标签: c

#include<stdio.h>

int main()
{
    struct MyBookPrice//tag
    {
        int bookid; //struct member1
        int price;      //struct member2
        char pubdate;   //struct member3

    }bookstruct;

    //assign value to the struct..
    bookstruct.bookid;
    bookstruct.price;
    bookstruct.pubdate;

    printf("\nGive new value to book ID: ");
    scanf("%d",&bookstruct.bookid);

    printf("\nGive new value to book Price: ");
    scanf("%d",&bookstruct.price);

    printf("\nGive new value of book Published Date: ");
    scanf("%s",&bookstruct.pubdate);//should be like 20/12/2017

    //accessing and display struct
    printf("\n New Labell =  %d",bookstruct.bookid);
    printf("\n New Label2 =  RM%d",bookstruct.price);
    printf("\n New Label3 =  %s",bookstruct.pubdate);

    system("pause");
    return 0;
}

大家好,从上面的代码......我可以执行程序......我可以输入bookstruct.bookid,bookstruct.price,&amp;的scanf值。 book.pubdate成功了......但是当它向下显示数据时...它只显示了bookstruct.bookid和bookstruct.price的值以及...最终崩溃..没有显示bookstruct.pubdate的值。

即时通讯使用dev-C ++ 5.11 ..你们可以帮助我在这里...我错了某地......提前做好了..

1 个答案:

答案 0 :(得分:1)

pubdate是一个char,因此无法读取超过1个字符。

因此,代码的行为是 undefined

另一种方法是使用char[]为该成员提供一定数量的元素。见Char arrays and scanf function in C