如何获取用于求和的结构值列表



我想从struct中获取所有的初始值来进行计算,但它总是以0向我显示total。它应该向我显示21的总值。任何能帮助我修复程序的人都将不胜感激。谢谢你复习我的问题。。(下面是我的代码和文本文件(

wbz.txt:

PID00001:Aircon:2
PID00002:Windows:10
PID00003:Pipe:9

我的代码:

#define SIZE 100
struct parts
{
char pid[50], pname[50];
int initialvalue;
}p[SIZE];
int main()
{
FILE* f;
char data[100], pid[50], * s, back;
int buf = 0, choice, i=0, total=0;
memset(p, 0, sizeof(p));
do {
printf("Which warehouse (1.WBZ | 2.WSL | 3.WAR): ");
scanf("%d", &choice);
if (choice == 1)
{ 
f = fopen("wbz.txt", "r");
while (fgets(data, sizeof data, f))
{
s = strtok(data, ":");
if (s != NULL)
{
strcpy(p[i].pid, s);
}
s = strtok(NULL, ":");
if (s != NULL)
{
strcpy(p[i].pname, s);
}
s = strtok(NULL, ":");
if (s != NULL)
{
p[i].initialvalue = atoi(s);
}
printf("nParts ID: %snParts Name: %snParts Quantity: %dn", p[i].pid, p[i].pname, p[i].initialvalue);

if (p[i].initialvalue < 10)
{
printf("n---------------------------------------");
printf("n%s unit is not enough, only %d leftn", p[i].pname, p[i].initialvalue);
printf("---------------------------------------n");
}
else
{
printf("n---------------------------------------");
printf("nThis unit is enoughn");
printf("---------------------------------------n");
}

}
if (i > 0)
p[i].initialvalue += p[i - 1].initialvalue;

if (++i == SIZE)
{
break;
}
p[i].initialvalue += p[i].initialvalue;
printf("nTotal: %d", p[i].initialvalue);
fclose(f);
}

printf("nDo you want to continue (y/n): ");
getchar();
scanf("%c", &back);
} while (back != 'n');

return 0;
}

您在递增i=之后使用自身更新p[i].initialVlue,因为您添加的值尚未设置:

// update should  be before the ++i and using previous index
If (i > 0) {p[i].initialvalue += p[i-1].initialvalue;}
if (++i == SIZE)
{
break;
}
} // end of while loop here
// next line is not good so remove it
//p[i].initialvalue += p[i].initialvalue;
// i is SIZE here do decrease it
// to get the last value
i—
printf("nTotal: %d", p[i].initialvalue);
}

此外,在使用它之前,您应该用0初始化p:

memset(p,0,sizeof(p));

最新更新