Why this code is not working ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why this code is not working ?

#include <stdio.h> int main() { int a, b; char ch; printf("Enter first number : \n"); scanf("%d", &a); printf("Enter second number : \n"); scanf("%d", &b); printf("Enter operator : "); scanf("%c", &ch); printf("%d %c %d", a, ch, b); return 0; }

17th Apr 2022, 5:31 PM
Samael
3 Answers
+ 4
Because a whitespace character was left in the input stream buffer from previous input reading. The leftover character gets accidentally assigned to variable <ch>. The leftover character was read in after reading variable <b>. Add a space before the %c conversion specifier, on reading <ch> to consume the leftover whitespace character from input stream buffer. scanf( " %c", &ch ); // notice the space before %c
17th Apr 2022, 6:28 PM
Ipang
+ 1
Ipang Thank u for your help
17th Apr 2022, 6:35 PM
Samael
0
Another option for using scanf and dropping the new line char. scanf("%c%*[^\n]", &variable_for_char); the %* is a suppression formatter: per the man pages -- An optional '*' assignment-suppression character: scanf() reads input as directed by the conversion specification, but discards the input. No corresponding pointer argument is required, and this specification is not included in the count of successful assignments returned by scanf(). This will not drop all white space on the new line. You can also: scanf("%c%*c", &variable_for_char); This will drop the very next char. The issue is the input buffer, best practice is to write code into a char* and parse as needed to protect against everything the user may enter, intentionally or unintentionally.
17th Apr 2022, 9:30 PM
William Owens
William Owens - avatar