2,160 views

2 Answers

Best answer
3 3 votes

%C does not skip any leftover whitespace( newline while entering the previous input ). It immediately reads that and returns.

But if we change the order of reading the inputs (char first)


	printf("enter a value");
	scanf("%c",&ch);
	printf("enter");
	scanf("%d",&a);

It works fine.

Possible Solutions :

1. Using an extra white space before %C specifier :

scanf(" %c",&ch);

2. or using getchar() in between to consume any newline feed in the input stream.

#include <stdio.h>
int main() {
int a;
	char ch;
	printf("enter");
	scanf("%d",&a);
	getchar();
	printf("enter a value");
	scanf("%c",&ch);

	return 0;
}

One more possible situation : 

There is a newline after every character in the input file which is consumed in the next iteration:

So to prevent this : using getchar() just after scanf():

• selected by
4 4 votes
since after entering a number an enter is pressed which is stored in stdin (keyboard buffer) so ch stores enter and dont need any input

soln either write fflush (stdin) or reverse the order of inputs and everything will be  fine
Position:
Show:

Related questions

9 9 votes
6 6 answers
1.0k
1.0k views
GO Classes asked Jul 25, 2025
1,008 views
#include <stdio.h void fun() { static int count = 0; count++; printf("%d ", count); } int main() { for (int i = 0; i < 3; i++) fun(); return 0; }What is the output of the...
6 6 votes
3 3 answers
703
703 views
GO Classes asked Jul 25, 2025
703 views
Given the pseudocode below for the function remains(), which of the following statements is true about the output, if we pass it a positive integer $n>2$ ? int remains(in...
7 7 votes
4 4 answers
768
768 views
GO Classes asked Jul 19, 2025
768 views
int arr[ ]={1, 2, 3, 4} int count; incr( ) {return ++count;} main( ) { arr[count++]=incr( ); printf("arr[count]=%d\n", arr[count]); }The value printed by the above progra...