I am trying to write a program in C where I intend to control the execution of a while loop according to user input in stdin. I am able to write the program in three different ways as following which perform as intended:
Using scanf() function
#include<stdio.h>
#include<string.h>
int main()
{
char loop= 'y';
while(loop=='y')
{
printf("Do you want to continue? [y|n]: ");
scanf("%c", &loop);
while(getchar() != '\n');
if(loop != 'y' && loop != 'n')
{
printf("Error! Please enter 'y' or 'n' \n");
loop = 'y';
}
}
return 0;
}
Using fgets() function
#include<stdio.h>
#include<string.h>
int main()
{
char loop[5]= "yes\n";
printf("%s",loop);
while(strcmp(loop,"yes\n")==0)
{
printf("Do you want to continue? [yes|no]: ");
if(strcmp(loop,"yes\n")!=0 && strcmp(loop,"no\n")!=0)
printf("Error! Please Enter 'yes' or 'no'\n");
else
fgets(loop,5,stdin);
}
return 0;
}
Using getch() from conio.h
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char loop= 'y';
while(loop=='y')
{
printf("Do you want to continue? [y|n]: ");
loop = getch();
printf("\n");
if(loop != 'y' && loop != 'n')
{
printf("Error! Please enter 'y' or 'n' \n");
loop = 'y';
}
}
return 0;
}
Although all the aforementioned methods perform the task of stopping or continuing the while
loop according to user input, the getch()
is little different. Using getch()
, the user does not have to press the enter after the user inputs y
or n
and the program terminates or continues as soon as the user provides input.
I am aware that conio.h
is not included in the standard gcc library and is frowned upon to use. However, I would like to implement the functionality of getch()
using either scanf()
or fgets()
or any other standard library function. By functionality of getch()
, I mean that as soon as a user press the desired key on terminal, the while
loop should terminate without needing to press the enter by the user.
Is it possible for either fgets()
or scanf()
to do this task?