Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

352
Views
Why is my program not working when I change the order of inputs?

I started learning C and tried to code this math program using switch statements. The program runs and works just fine when I scan the operator first and then scan the numbers. But if I switch the order of the scanf functions to take the numbers first and then the operators, the program takes the number but after that it does not take the second input (the operator) and just prints the default value (invalid input). Why is this happening?

I have provided the code (if I run this code, the problem occurs with the program just taking the numbers and not taking the operators. But of the order is flipped, it works).

#include <stdio.h>

int main()
{

    float a, b, result;
    char operator;

    printf("Enter 2 numbers:");
    scanf("%f %f", &a, &b);
    printf("Choose a math operator (+, -, *, /):");
    scanf("%c", &operator);

    switch (operator)
    {
    case '+':
        result = a + b;
        break;
    case '-':
        result = a - b;
        break;
    case '*':
        result = a * b;
        break;
    case '/':
        result = a / b;
        break;
    default:
        printf("\nInvalid operator");
        return -1;
    }
    printf("%f", result);
    return 0;
}
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The format string "%c" will read the newline character from the first line of input. What you want instead is " %c" which will skip leading whitespace, so replace the line

scanf("%c", &operator);

with

scanf(" %c", &operator);

See also https://pubs.opengroup.org/onlinepubs/9699919799/

A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread.

over 4 years ago · Santiago Trujillo Report

0

you need to change

scanf("%c", &operator);

to

scanf("%s", &operator);

it will run.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!