2

I have tried following code there is require %d before entering character. That is an after switch loop in code.

#include<stdio.h>
#include<conio.h>
void sum();
void mul();
void main()
{
char ch;
int c;
clrscr();
do
{
    printf("\n\n Enetr choice ");
    printf("\n\n\t 1: SUM \n\n\t 2: MUL");
    scanf("\n\n\t %d",&c);
    switch(c)
    {
        case 1:
            sum();
            break;
        case 2:
            mul();
            break;
        default:
            printf("\n\n hhhh..... ");
    }
    printf("\n\n Want u calcualte again");
    //scanf("%d");
    scanf("%c",&ch);
    printf("\n ch value is %c",ch);
}while(ch=='y'|| ch=='Y');
getch();
}
void sum()
{
int s;
s=10+50;
printf(" SUM: %d",s);
}
void mul()
{
int s;
s=10*50;
printf(" SUM: %d",s);
}  

Here in this code after switch I tried to input character but without the scanf statement which is in comment is require while you input character. without that scanf statement compiler does not take character input. so please give me solution.

Shivaji More
  • 310
  • 1
  • 2
  • 9

4 Answers4

6

Its because you have to "eat up" the newline from previous input

You don't have to use %d.

Instead use:

while((c = getchar()) != '\n' && c != EOF) ;

in place of

//scanf("%d");

to discard the newline.

P0W
  • 46,614
  • 9
  • 72
  • 119
2

this is the problem occurred due to the insertion of next line character i.e. '\n' instead of following statement

scanf("%c",&ch);

you should use

scanf("\n%c",&ch);

Now what will happen firstly control goes to new line and then it will insert or input the character, just change this statement you will find your program execute properly...

Vaibhav
  • 136
  • 1
  • 3
  • 13
  • Whitespace characters in scanf format strings do not behave the way you think they do. – mlp Aug 25 '13 at 11:39
1

You have to consume new line character. You can add space before %c in your scanf statement to ignore white space


You should change

scanf("%c",&ch);

to

scanf(" %c",&ch);//this makes scanf ignore white spaces like new line, space etc.

or use getchar() to do it.

c=getchar();

For more insight go to question:
scanf() function doesn't work?

Community
  • 1
  • 1
Himanshu Pandey
  • 726
  • 5
  • 13
0

Another method that tells scanf to consume or recognize white space (and a new line is considered white space) is to code:

  char ch[2];
  ...
  scanf("%1s", &ch);
  ...
  if (ch[0] == 'x' etc.
JackCColeman
  • 3,777
  • 1
  • 15
  • 21