Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf won't ask for input the second time [duplicate]

Tags:

c

scanf

#include "stdio.h"

int main(void)
{

     int order, nextp, N=3;
     char cont;
     nextp = 0;
     printf("\nShould we continue (y or n): ");
     scanf("%c", &cont);
     if (cont != 'y') return;
     for(; nextp < N; nextp++)
     {
        printf("Enter order number: ");
        scanf("%d", &order);
        printf("you have entered %d\n", order);
        printf("okay now continue with cont\n");


        printf("enter cont y or n: ");
        scanf("%c", &cont);
        if (cont != 'y')
        {
            printf("\nnot equal to y\n");
            break;
        }
        printf("after intepreting t[0]");
      }

   return 0;
}

The output looks like this

Should we continue (y or n): y
Enter order number: 45
you have entered 45
okay now continue with cont
enter cont y or n: 
not equal to y

The second input was skipped. Why?

like image 608
user1012451 Avatar asked Nov 14 '12 04:11

user1012451


2 Answers

because of newline character already in stdin , this is happening. use

scanf(" %c", &cont); 

instead of

scanf("%c", &cont);

note one space before %c.

like image 126
user2670535 Avatar answered Nov 14 '22 23:11

user2670535


After scanf("%d", &order); consumes the number (45 in this case), there is still a newline left after that. You can use scanf("%d\n", &order) to make it consume the return.

Another answer to this can be found here:

scanf() leaves the new line char in buffer?

like image 42
zw324 Avatar answered Nov 15 '22 00:11

zw324