I would like to take all of the initial value from struct to do calculate, but it always show total in 0 to me. It supposed to show me a total value of 21.. Anyone that can help me to fix my program I will be very appreciated. Thank you for reviewing my question.. (Below is my code and text file)
wbz.txt:
PID00001:Aircon:2
PID00002:Windows:10
PID00003:Pipe:9
My Code:
#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: %s\nParts Name: %s\nParts Quantity: %d\n", 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 left\n", p[i].pname, p[i].initialvalue);
printf("---------------------------------------\n");
}
else
{
printf("\n---------------------------------------");
printf("\nThis unit is enough\n");
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;
}
CodePudding user response:
You update p[i].initialVlue using itself after having incremented i = you add 0 to 0 because the value you add is not yet set :
// 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);
}
Also you should initialise p with 0 before using it :
memset(p,0,sizeof(p));
