Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

353
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

you need to change

scanf("%c", &operator);

to

scanf("%s", &operator);

it will run.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda