The program does not stop on the scanf line ("% c", & ch), why?

the program does not stop on the scanf line ("% c", & ch). why this is happening, can someone explain this to me?

#include<stdlib.h> #include<stdio.h> struct list { char val; struct list * next; }; typedef struct list item; void main() { char ch; int num; printf("Enter [1] if you want to use linked list or [2] for realloc\n"); scanf("%d", &num); if(num == 2) { scanf("%c", &ch); printf("%c", ch); } } 
+6
source share
2 answers

Say you enter 2 when you read a number. The actual input stream will be 2 \ n (\ n is a newline character). 2 goes into a number, and \ n remains, which goes into ch. To avoid this, add a space in the format specifier.

 scanf(" %c", &ch); 

This ignores any spaces, newlines or tabs.

+13
source

The reason for this is the newline character \n left behind by the previous scanf when you press Enter for the next scanf reading. When statement

 scanf("%c", &ch); 

then it reads that \n left behind by the previous scanf .
To eat this \n , you can use the space before the %c specifier. The space in front of the %c specifier can eat any number of space characters.

 scanf(" %c", &ch); ^ a space 
+4
source

Source: https://habr.com/ru/post/959104/


All Articles