Reputation: 167
I have to do a program for class that is using parallel arrays to store data of a students grades. We are to give the arrays data by using the Linux command "<" when executing the program.
./a.out < inputfile
However, when I run the program I get an infinite loop of the menu that program is using to access the data in the arrays. It looks like the program is skipping the function I'm using to populate the arrays from the function and using the data from the file for the menus scanf() that is in a separate function.
Here is the function that I'm using to populate the arrays:
void populate(int idarray[],int testone[], int testtwo[],float hw[],int max)
{
int counter = 0;
while(scanf("%d", &idarray[counter]) != EOF)
{
if(idarray[counter] != -1)
{
//scanf("%f %d %d", &hw[counter], &testone[counter], &testtwo[counter]);
scanf("%f",&hw[counter]);
scanf("%d",&testone[counter]);
scanf("%d",&testtwo[counter]);
counter++;
}
if(counter == max-1)
break;
}
}
"max" is the bounds of the arrays.
the input file would look like:
1983990 75.6 39 78 1935440 50.03 78 34
Upvotes: 0
Views: 97
Reputation: 927
Check whether your while loop breaks because of counter == max - 1 or by EOF. If it is by the former then you will still be having inputs in stdin which will be given as input to your menu choices without your control
Explanation: If your while loop breaks because of "counter == max -1" that means your "max"(array size) is lesser than the total number of inputs(decimal numbers) present in your input file. If your "max"(array size) is appropriate then it will break only by EOF. Now if the while breaks before reaching EOF, that means you have not consumed all of the input decimal numbers you have passed to stdin, meaning there will be input numbers left to be consumed even after termination of your while loop. This yet to be consumed inputs will be consumed (in other words will be given as input to) by your menu choice's "scanf" (which get the choice for the next action). That is the reason for the cursor not waiting for you to give input to your menu choice
You can also forcefully clear your stdin buffer by following the answer( I am not able to flush stdin), just before calling your menu function, so that it will wait for your input choice
Upvotes: 1
Reputation: 180058
I don't see anything deeply wrong with your function, but your termination criterion appears to be off by one. Off by two, really, if it is tested where you are testing now. Think about what happens when max
is 0 or 1.
To accommodate the possibility that max
is 0, you need to test the termination condition (correctly) at the very beginning of each loop iteration, before reading anything.
Also, I tend to prefer testing inequalities instead of equalities, as that does a better job of reigning misbehavior when I get my indexing a bit wrong. So in this case I would either break when counter >= max
or perform an iteration only when counter < max
.
Upvotes: 0