Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The program doesn't stop on scanf("%c", &ch) line, why? [duplicate]

Tags:

c

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);
    }
}
like image 429
Aviram Shiri Avatar asked Nov 30 '13 23:11

Aviram Shiri


People also ask

What does %C do in scanf?

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.

What is the use of %C in c?

%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.

How do I stop scanf from reading?

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.

Is there %C in c?

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.


2 Answers

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.

like image 72
Paul92 Avatar answered Oct 24 '22 14:10

Paul92


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
like image 21
haccks Avatar answered Oct 24 '22 13:10

haccks