While loop not stopping for scanf for some reason. please help!
Ok I have a while loop here which contains a switch statement (I have only fleshed out case 1) and functions normally , except for when in case 1 I hit CTRL-D (for EOF, could be CTRL-Z for you). This sends it into an infinite loop and ignores the scanf at the top of the while loop, which it would usually stop at. I do not understand why. Does anyone know?
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAXLINES 5
int main (void)
{
int counter=1;
float data[MAXLINES];
int array_index=0;
int x;
int menu_selection = 1;
int program_continue = 1;
while (program_continue == 1)
{
printf("This program will perform the following: 1,2,3\n");
printf("select 1,2,3\n");
scanf("%d",&menu_selection);
x=1;
switch (menu_selection)
{
case 1:
while ( (array_index <= MAXLINES-1) )
{
printf("enter data line #%d:",counter);
scanf("%f",&data[array_index]);
array_index++;
counter++;
if ( ( x=getchar() ) == EOF)
array_index = MAXLINES+1;
}
if (counter > MAXLINES)
printf("\n\nNumber of data lines: %d\n",counter-1);
if (counter < MAXLINES)
printf("\n\nNumber of data lines: %d\n",counter-2);
array_index = 0;
break;
case 2:
printf("continuing\n\n");
break;
case 3:
printf("goodbye!");
program_continue = 0;
break;
default: printf("That is not a valid entry.\n");
}
}
return 0;
}