Nous Sa Smily
Nous Sa Smily

Reputation: 83

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

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

Upvotes: 8

Views: 8285

Answers (2)

zwol
zwol

Reputation: 140846

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

Upvotes: 3

R Sahu
R Sahu

Reputation: 206717

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;
}

Upvotes: 10

Related Questions