the program doesnt stop on scanf("%c", &ch) line. why does it happens sombody can please 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);
}
}
A simple type specifier consists of a percent (%) symbol and an alpha character that indicates the type. Below are a few examples of the type specifiers recognized by scanf: %c — Character. %d — Signed integer.
%d is used to print decimal(integer) number ,while %c is used to print character . If you try to print a character with %d format the computer will print the ASCII code of the character.
If you use a %d format specifier, a decimal point will stop the reading. Furthermore, if you use a %f format specifier and the user types an integer, scanf will convert the integer to a floating point value.
The format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, etc.
Let's say you input 2 when you're reading for num. The actual input stream will be 2\n (\n is the newline character). 2 goes into the num, and there remains \n, which goes into ch. To avoid this, add a whitespace in format specifier.
scanf(" %c", &ch);
This will ignore any whitespaces, newlines or tabs.
The reason behind this is the newline \n character left behind by previous scanf, when pressing Enter key, for the next read of scanf. When the statement
scanf("%c", &ch);
executed then it reads that \n left behind by the previous scanf.
To eat up this \n you can use a space before %c specifier. A space before the %c specifier is able to eat up any number of white-space characters.
scanf(" %c", &ch);
^ a space
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With