+ 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; }
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
+ 1
Ipang Thank u for your help
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.