I have read previous questions regarding this problem too. fflush(stdin) does not work in this scenario for me. I want my program to read from a piped stdin and continue from keyboard input in the middle.
int main()
{
int userin = 3;
read_input();
userin = print_menu();
userin = parse_input(userin);
return 0;
}
I want to read data from a file which is passed to the program as a pipied stding like
program < testing_text
int read_input(){
char line[200];
char word[MAX_STRING+1];
int line_number = 0;
while(fgets(line, sizeof(line), stdin) != NULL ){
//do something
printf("%s",line);
line_number++;
}
}
Now read_input must finish reading from the piped input. 'print_menu' must continue reading from the keyboard.
int print_menu()
{
int userinput;
char c;
char num[4];
while((c=getchar()) != '\n' && c != EOF && c != '\r');
printf("\n1. Choice 1 \n");
printf("2. Choice 2\n");
printf("3. Exit\n");
printf("Enter your choice (1-3): ");
/* scanf("%d", &userinput); */
/* fgets(num,80,stdin); */
scanf("%s", num);
userinput = atoi(num);
return userinput;
}
int parse_input(int userinput)
{
char num[4];
while( userinput > 3 || userinput < 1 ){
printf("Sorry, that is not a valid option\n");
printf("Enter your choice (1-3): ");
scanf("%s", num);
userinput = atoi(num);
/* scanf("%d", &userinput); */
/* while( (c = getchar()) == '\n'); */
}
return userinput;
}
My output is a infinite loop of
Enter your choice (1-3): Sorry, that is not a valid option
When I remove read_input method and piped stdin program works fine. I cannot figure out a get around for this, does someone has a idea..