How to loop with invalid object message?

Asked

Viewed 89 times

0

I am only doing this program to train, and I want to print a message saying "invalid object" if what I type is different from the solids that will be declared in the variables, but with a loop while to return so that I can type the solid again. But if I print the invalid object message within the function do it will print the first time even if I type a valid object.

void main()
{
    system("cls");
    setlocale(LC_ALL, "");

    int comp;
    float raio, alt;
    char sld[19];
    char cil[9] = "cilindro";

        printf("\t\t ========== Calculadora de Volume ==========");

        do
        {
            printf("\n\n Digite o sólido: ");
            fgets(sld, 61, stdin);
            fflush(stdin);

            comp = strcmp(sld, cil);
        } 
        while (comp != 0);
  • can place the condition within an if: if (comp != 0) printf("objeto inválido"); plain as that

1 answer

0


Do not make use of the do-while, Make an infinite loop and make a decision within whether or not you will continue within the loop according to the established condition, so you can do what you wish. You can even use this construction, but you either have to duplicate the condition, or create a flag or make a very confusing code.

I took advantage and fixed other code problems:

#include <stdio.h>
#include <string.h>

int main() {
    char sld[19];
    printf("\t\t ========== Calculadora de Volume ==========");
    while (1) {
        printf("\nDigite o sólido: ");
        fgets(sld, 18, stdin);
        sld[strcspn(sld, "\n")] = 0;
        if (strcmp(sld, "cilindro") == 0) break;
        printf("\nObjeto inválido");
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.