'when there is no successful assignments' i know that scanf returns 0 to indicate it, but is that the only thing that it does? this is my code:
#include<stdio.h>
int main(void) {
int val,x;
x=scanf("%d",&val);
if(x==1)
printf("success!");
else{
printf("try again\n");
scanf("%d",&val);
}
return 0;
}
if i enter a number, it works fine but if i enter a character scanf doesn't work anymore, this is what i get:
k
try again
process returned 0 (0x0) execution time :2.578 s
press any key to continue.
_
meaning that it doesn't allow me to enter a new value, why is that? is there something wrong in the code? if yes how can i fix it? should i stop using scanf?
This happens because every scanf() leaves a newline character in a buffer that is read by the next scanf. How to Solve the Above Problem? We can make scanf() to read a new line by using an extra \n, i.e., scanf(“%d\n”, &x) . In fact scanf(“%d “, &x) also works (Note the extra space).
You may've used the scanf inside a while loop or for loop or do while loop or if else statement or switch case statement or in a remote user defined function that doesn't satisfy the condition to enter into it. In that case that block will be skipped and scanf will not work.
The scanf() function It returns the number of input values that are scanned. If there is some input failure or error then it returns EOF (end-of-file).
When scanf
doesn't work, the invalid data is still left in the stream. You'll have to read and discard the data from the stream first before you can enter more data.
#include<stdio.h>
int main(void) {
int val,x;
x=scanf("%d",&val);
if(x==1)
printf("success!");
else{
// Discard everything upto and including the newline.
while ( (x = getchar()) != EOF && x != '\n' );
printf("try again\n");
scanf("%d",&val);
}
return 0;
}
The scanf
family of functions are broken-as-specified and should never be used for anything.
The correct way to write this program is to use getline
, if available, or fgets
otherwise, to read an entire line of user input. Then use strtol
to convert the input to a machine integer, taking care to check for errors:
errno = 0;
result = strtol(line, &endptr, 10);
if (endptr == line || *endptr != '\n' || errno)
// invalid input
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With