Reputation: 151
I'm working on some homework for an intro to C class, in which we must write a program that reads input from a text file that contains order information from a winery. I've got everything written out, but when I run it, the only thing that prints properly is "Winery #1:" and then the window errors out. I tried to print one of my arrays out at the end of the program to see what the problem was, and then I got an error that states:
|54|error: subscripted value is neither array nor pointer|
I understand what the error means, though I am not sure what I need to do to correct it. I believe I have properly declared my arrays and such, but I still get the error. This is the code I have:
int main () {
//Creates the file pointer and variables
FILE *ifp;
int index, index2, index3, index4;
int wineries, num_bottles, orders, prices, sum_order, total_orders;
//Opens the file to be read from.
ifp = fopen ("wine.txt", "r");
//Scans the first line of the file to find out how many wineries there are,
//thus finding out how many times the loop must be repeated.
fscanf(ifp, "%d", &wineries);
//Begins the main loop which will have repititions equal to the number of wineries.
for (index = 0; index < wineries; index ++) {
//Prints the winery number
printf("Winery #%d:\n", index + 1);
//Scans the number of bottles at the aforementioned winery and
//creates the array "prices" which is size "num_bottles."
fscanf(ifp,"%d", num_bottles );
int prices[num_bottles];
//Scans the bottle prices into the array
for (index2 = 0; index2 < num_bottles; index2++)
fscanf(ifp, "%d", &prices[index2]);
//Creates variable orders to scan line 4 into.
fscanf(ifp, "%d", &orders);
for(index3 = 0; index3 < orders; index3++){
int sum_order = 0;
for(index4 = 0; index4 < num_bottles; index4++)
fscanf(ifp, "%d", &total_orders);
sum_order += (prices[index4] * total_orders);
printf("Order #%d: $%d\n", index3+1, sum_order);
}
}
printf("%d", prices[index2]);
fclose(ifp);
return 0;
}
I looked at some of the other answers on this site, but none of them seemed to help me with my problem. I get the sinking feeling that the answer is looking me in the face, but being the tired amateur coder I am, I haven't been able to find it. Thanks in advance!
Upvotes: 0
Views: 621
Reputation: 121387
There are two prices
One is array inside the for loop and another is int outside the loop. So prices[num_bottles]
is no longer there when you try to print it at the end, where only the int prices is there. Obviously, int prices can't used as prices[index2]
.
Take out the prices from inside the for loop and put it at the top.
Upvotes: 1
Reputation: 48290
Change
//Scans the number of bottles at the aforementioned winery and
//creates the array "prices" which is size "num_bottles."
fscanf(ifp,"%d", num_bottles );
to
//Scans the number of bottles at the aforementioned winery and
//creates the array "prices" which is size "num_bottles."
fscanf(ifp,"%d", &num_bottles );
// ^
Upvotes: 0