How to return to the menu after performing function?

Asked

Viewed 1,809 times

-1

I would like to know how to do after adding it() just returned to the menu. Someone helps?

#include <stdio.h>
#include <stdlib.h>

    char descricao[40];

    void adicionar(){
        FILE * pFile;

        printf("ESCREVA: ");
        fgets (descricao,39,stdin);
        pFile = fopen ("log.txt","a");
        fputs (descricao,pFile);
        fclose (pFile);
        fflush(stdin);
        getchar();
    }

    void menu(){
        int opcao;

        while (1){
        puts("1... Adicionar artigo");
        puts("2... Sair");

            scanf("%d", &opcao);

            switch (opcao){
            case 1:
                adicionar();
                break;
            case 2:
                exit(0);
            }
        }
    }

    int main(){
        menu();
    }
  • Is there a problem? It seems to be all right.

2 answers

0

The fflush function cleans the buffer of the file passed as parameter, so you should clear the keyboard buffer before reading.

#include 
#include 
char descricao[40];

void adicionar(){
    FILE * pFile;

    printf("ESCREVA: ");
    fflush(stdin);
    fgets (descricao,39,stdin);
    pFile = fopen ("log.txt","a");
    fputs (descricao,pFile);

    fclose (pFile);
}

void menu(){
    int opcao = 0;

    while (opcao != 2){
        puts("1... Adicionar artigo");
        puts("2... Sair");
        scanf("%d", &opcao);
        switch (opcao){
            case 1:
                adicionar();
                break;
        }
    }
}

int main(){
    menu();
}

0

The simplest solution is

// ...
int main() {
    for (;;) menu();
}

Browser other questions tagged

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