I'm just starting C language classes, and I have searched around to understand why that part of my code behaves the way it does and come to find this site, a page titled "Warning against Scanf" where it says scanf() is less prone to errors when it's used along with fgets().
Now, we haven't studied fgets() yet and I don't know the correct syntax for it. This is the part of my code that causes a problem.
=============== =============== =============
/*asks a user to enter a number less than 25 and gives a warning if a number greater than 25 is entered*/
int x=26;
printf("enter a number");
while(x>25)
{
scanf("%d",&x);
if(x>25)
printf("Enter a number less or equal to 25");
else
printf("the number you entered is %d",x);
}
=============== =============== =============== =
Now this segment works fine as long as the user enters a number, but it starts acting weird if a character or an array of characters is entered.
how do I use fget() in this case? and is there a way to handle this issue without using fget()? like tweaking scanf() or something?
Now, we haven't studied fgets() yet and I don't know the correct syntax for it. This is the part of my code that causes a problem.
=============== =============== =============
/*asks a user to enter a number less than 25 and gives a warning if a number greater than 25 is entered*/
int x=26;
printf("enter a number");
while(x>25)
{
scanf("%d",&x);
if(x>25)
printf("Enter a number less or equal to 25");
else
printf("the number you entered is %d",x);
}
=============== =============== =============== =
Now this segment works fine as long as the user enters a number, but it starts acting weird if a character or an array of characters is entered.
how do I use fget() in this case? and is there a way to handle this issue without using fget()? like tweaking scanf() or something?
Comment