6
#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?

user1012451
  • 3,343
  • 7
  • 29
  • 33
  • This has been discussed a zillion times on SO. Try doing a little research on existing questions – fkl Nov 14 '12 at 04:52

5 Answers5

11

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

scanf(" %c", &cont); 

instead of

scanf("%c", &cont);

note one space before %c.

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
user2670535
  • 129
  • 1
  • 2
  • 6
4

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?

Community
  • 1
  • 1
zw324
  • 26,764
  • 16
  • 85
  • 118
3

This is why scanf is not typically preferred for character input. There's a left over carriage return after the previous input.

For example, if you were to add a getchar() after the order input, your problem would be solved, but that's not clean code. You can also see this explicitly by subsituting cont != 'y' to cont != '\n'.

Instead, use getchar() for all your input and check for \n

John
  • 2,675
  • 2
  • 18
  • 19
  • Okay I will try that in a bit. But I tried `fgets(..)` and it suffers too and it was supposed to be safer. – user1012451 Nov 14 '12 at 04:18
  • Again, fgets includes the newline at the end. Simply replace the newline with a null before inputting the value – John Nov 14 '12 at 04:19
1

For most conversions scanf will skip whitespace, but for char format ("%c") you must skip white space by using an explicit space in the format (" %c") as explained here:

C - trying to read a single char

This is also explained in the scanf documentation, but it's confusing and may be better to use something else as others have mentioned.

Community
  • 1
  • 1
monex0
  • 238
  • 1
  • 8
1

You can use fflush()

printf("enter cont y or n: ");
fflush(stdin);
scanf("%c", &cont);
sushant goel
  • 821
  • 6
  • 8