When scanf returns 0 in c and just doesn't work

'when there are no successful assignments, I know that scanf returns 0 to indicate it, but is that the only thing 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 the file, then scanf no longer works, this is what I get:

  k try again process returned 0 (0x0) execution time :2.578 s press any key to continue. _ 

means that it does not allow me to introduce a new value, why? Is there something wrong in the code? if so, how can I fix this? should i stop using scanf?

+5
source share
2 answers

When scanf does not work, invalid data still remains in the stream. You will first need to read and discard the data from the stream 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; } 
+7
source

The scanf family of functions is broken up as indicated 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 the entire user input line. Then use strtol to convert the input to an integer of the machine, taking care of the error:

 errno = 0; result = strtol(line, &endptr, 10); if (endptr == line || *endptr != '\n' || errno) // invalid input 
+3
source

Source: https://habr.com/ru/post/1239604/


All Articles