m0_62267751 2021-12-20 15:28 采纳率: 85.7%
浏览 37
已结题

C语言 静态结构体插入数据,插入后想依次输出出来,但是没有反应 直接结束


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct Cate
{
    int No;
    char Name[30];
};
int main(){
    struct Cate ca[10]=
    {
        {1,"Starter"},
        {2,"Curries"},
        {3,"Barbecues"}
    };
    char str[100]={0};
    int i=3;
    int n;
    do{
    printf("Input:");//输入新的str 把它作为新的元素插入结构体中变成ca[4]
    scanf("%s",str);
    
    strcpy(ca[i+1].Name,str);//因为可能继续插入,所以用了一个i
    
    ca[i+1].No=i+1;
    
    printf("%s\n",ca[i+1].Name);
    printf("%d\n",ca[i+1].No);
    i++;
    
    printf("Enter n:");//如果n等于1,就返回继续输入
    scanf("%d",n);
    }while(n==1);
    
    int j=0;//如果n不等于1,就把所有的结构体元素输出
    for(j=0;j<i;j++)
    {
        printf("%d\t%s\n",ca[j].No,ca[j].Name);
    }
    
    return 0;
}

img

  • 写回答

1条回答 默认 最新

  • qzjhjxj 2021-12-20 15:40
    关注

    修改如下,供参考:

    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    struct Cate
    {
        int No;
        char Name[30];
    };
    int main() {
        struct Cate ca[10] =
        {
            {1,"Starter"},
            {2,"Curries"},
            {3,"Barbecues"}
        };
        char str[100] = { 0 };
        int i = 3;
        int n;
        do {
            printf("Input:");//输入新的str 把它作为新的元素插入结构体中变成ca[4]
            scanf("%s", str);
            strcpy(ca[i].Name, str);//strcpy(ca[i + 1].Name, str);//因为可能继续插入,所以用了一个i
            ca[i].No = i + 1;    //ca[i + 1].No = i + 1;
            printf("%s\n", ca[i].Name); //printf("%s\n", ca[i + 1].Name);
            printf("%d\n", ca[i].No); //printf("%d\n", ca[i + 1].No);
            i++;
            printf("Enter n:");//如果n等于1,就返回继续输入
            scanf("%d", &n);   //scanf("%d", n);
        } while (n == 1);
        int j = 0;//如果n不等于1,就把所有的结构体元素输出
        for (j = 0; j < i; j++)
        {
            printf("%d\t%s\n", ca[j].No, ca[j].Name);
        }
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 12月28日
  • 已采纳回答 12月20日
  • 创建了问题 12月20日