gpt4 book ai didi

C If 循环设置结构数据失败

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:25 27 4
gpt4 key购买 nike

这几天一直困扰着我。我尝试过搜索,但发现的大多只是 struct...

的定义

在 if 循环中,我设置了 2 个结构变量,但结果都不正确。 guests[x].plusone 卡在 0 而 guests[x].plusonefood 只是空的。但是,如果我将它们(使用同一行)设置在循环之外,则没有问题。我的编译器没有显示任何警告或错误。我错过了什么?

这是我使用 C 的第一个项目,所以请指出您注意到的任何其他问题。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct guestinfo
{
char name[50];
short int plusone;
char food[50];
char plusonefood[50];
};

char temp[5];

char setfood (int f)
{
char foodtemp[f];

int x;
for (x=0; x < f; x++)
{
printf("Food option %d:\n", (x+1));
fgets(&foodtemp[x],100,stdin);
}

return *foodtemp;
}

int main ()
{

int number_of_rsvp=0;
int number_of_food=0;

printf("Number of food choices:\n");
fgets(temp,5,stdin);
number_of_food = atoi (temp);

while (number_of_food <= 0)
{
printf("Please enter a number greater than 0\n");
fgets(temp,5,stdin);
number_of_food = atoi (temp);
}

char food [50] [number_of_food];
**food = setfood(number_of_food);

printf("Number of RSVPs:\n");
fgets(temp,5,stdin);
number_of_rsvp = atoi (temp);

while (number_of_rsvp <= 0)
{
printf("\nPlease enter a number greater than 0\n");
fgets(temp,5,stdin);
number_of_rsvp = atoi (temp);
};

struct guestinfo guests[number_of_rsvp];

int x;
int f;
for (x=0; x < number_of_rsvp; x++)
{
// add input validation to this section
printf("Guest Number %d:\n\nGuest Name:\n", (x+1));
fgets(guests[x].name,50,stdin);
printf("Food Choice #:\n");
fgets(temp,3,stdin);
f = atoi(temp);
f--;
*guests[x].food = food [50] [f];
printf("Plus One? Y/N\n");
fgets(temp,3,stdin);
}

if (strchr (temp,'Y') != NULL || strchr (temp,'y') != NULL) //This loop
{
guests[x].plusone = 1;
printf("Plus one food choice #:\n");
fgets(temp,3,stdin);
f = atoi(temp);
f--;
*guests[x].plusonefood = food [50] [f];
}

else if (strchr (temp,'N') != NULL || strchr (temp,'n') != NULL)
{
guests[x].plusone = 0;
};


FILE *guestlist = fopen ("guestlist.txt","w");
// debugging
printf("%d\n",guests[0].plusone);
printf("%s\n",guests[0].plusonefood);


for (x=0; x < number_of_rsvp; x++)
{
fprintf(guestlist,"Guest Number %d:\n\nName: %s\nFood Choice: %s\n",(x+1),guests[x].name,guests[x].food);

switch (guests[x].plusone)
{
case 1:
{
fprintf(guestlist,"Plus One: Yes\n\tPlus One Food: %s\n\n",guests[x].plusonefood);
break;
}
case 0:
{
fprintf(guestlist,"Plus One: No\n\n");
break;
}
default:
{
break;
}
}
}

fclose (guestlist);

printf("Printing Guest List...\n");


return 0;
}

最佳答案

问题是您正在访问无效的内存位置。
该数组有 number_of_rsvp 个元素。
您的 for() 循环遍历变量 x 直到值 number_of_rsvp 并退出。
之后,x的值等于number_of_rsvp
由于数组的索引只能从 0number_of_rsvp - 1,元素 guests[x],即 guests [number_of_rsvp],超出范围。

关于C If 循环设置结构数据失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25561405/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com