0

Why won't the last scanf work?

The last scanf won't work. User isn't allowed to perform the input. Code: #include <stdio.h> // Compiler version gcc 6.3.0 // int main() { float num1, num2; char ch; printf("Enter the first number: "); scanf("%f", &num1); printf("\nEnter the second number: "); scanf("%f", &num2); printf("\nEnter the operator (+, -, /, *): "); scanf("%c", &ch); printf("\nOperator choosen: %c", ch); if (ch == '+') { float answer = num1 + num2; printf("%f", answer); } else if (ch == '-') { float answer = num1 - num2; printf("%f", answer); } else if (ch == '/') { float answer = num1 / num2; printf("%f", answer); } else if (ch == '*') { float answer = num1 * num2; printf("%f", answer); } else {printf("Error");} return 0; }

26th Feb 2022, 6:16 AM
Ashok Ighe
Ashok Ighe - avatar
3 Antworten
+ 4
scanf() reads input and stops when it sees a whitespace. When in console, we give input by typing the input and press Enter key. The input is read in by scanf(), but the character given by Enter key is left in. This is usually not a problem when the next reads was for numeric data e.g. integers or floating point types, because scanf() skips whitespaces in the beginning of input. For example, read an integer, and provide spaces before the number " 2022" scanf() will still read the value. Problem comes when `char` or C-String (`char` array) was expected. In such event, the leftover character gets accidentally read in and assigned to the receiving variable, cause unlike numeric types, `char` or C-String allows such input.
26th Feb 2022, 7:43 AM
Ipang
+ 2
The problem is because there is a character left behind in the input stream after reading <num2>. The leftover character is then read in as we read <ch> instead of the actual symbol entered by user, and that's why it was considered invalid operator selection. You can verify this by checking the ASCII value of <ch> in the `else` block else { printf( "Error invalid operator %d\n", ch ); } This will output 10 (ASCII code for '\n'), assuming you entered all inputs in separate lines. To overcome this, you can put a space before the conversion specifier %c when reading <ch> scanf( " %c", &ch ); // notice a space before %c
26th Feb 2022, 6:47 AM
Ipang
+ 2
Ipang Thank you for answering. Things I need to clear: 1. How did the character got left in the input stream? 2. Why it didn't got left in the first scanf?
26th Feb 2022, 7:08 AM
Ashok Ighe
Ashok Ighe - avatar