Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

scanf

'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?

like image 446
Nous Sa Smily Avatar asked Dec 31 '15 23:12

Nous Sa Smily


People also ask

Why scanf function is not working?

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).

Why is scanf not taking input in C?

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.

What does scanf return failed?

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).


2 Answers

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;
}
like image 197
R Sahu Avatar answered Sep 28 '22 14:09

R Sahu


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
like image 28
zwol Avatar answered Sep 28 '22 14:09

zwol