How to return to the menu after executing function?

-1

I would like to know how to do it after adding it () to the menu. Does anyone help?

#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();
    }
    
asked by anonymous 14.05.2016 / 23:59

2 answers

0

The fflush function clears the buffer of the file passed as a 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();
}
    
15.05.2016 / 04:38
0

The simplest solution is

// ...
int main() {
    for (;;) menu();
}
    
16.05.2016 / 11:04