can someone tell me why it doesnt rewind.

–2 votes
asked Sep 13, 2019 by Jongbo (460 points)
while(1){
       
       printf("1.already a member? Log in\n");
       printf("2.register\n");
       
       
       if(scanf("%d",&rAns)==0){
           
           
           printf("enter right answer\n");
           rewind(stdin);
       }
       
       else{
           if(rAns<1 || rAns>2 ){
               printf("enter one of the options\n");
               
           }
           else{
               break;
           }
       }
   }

I made if statement that if the scanf scans wrong data type than what it supposed to get it should go back to beginning of loop and start again. but appearantly the rewind is not working so the buffer is with wrong input. I want to know how to rewind my answer in my code.

1 Answer

0 votes
answered Oct 27, 2019 by Redstoneboi (540 points)
edited Oct 28, 2019 by Redstoneboi

EDIT: rewind() is a thing. I didn't know. But anyway, what you should do is:

if(scanf("%d", &rAns)==0){
    printf("enter right answer\n");
    rewind(stdin);
}

it should be:

char rAns = 0;
while(!scanf("%d", &ans)) {
    printf("Please input a number.\n");
}

Now it loops while the input is invalid.

You can now remove the else { }.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...