#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;
}
修改如下,供参考:
#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;
}