Even using fflush, the fscanf function is not working

Asked

Viewed 142 times

-1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
struct cadastro{
    char nome[30];
    float notas[1][4];
    int faltas;
}alunos[3];

void LimpaTela(){//função para limpar a tela
    system("cls");
}

void incluir(struct cadastro inclusao[]){
    FILE *arq;

    printf("\tFaça o cadastro dos alunos...\n");
    arq = fopen("arquivo.txt", "w");
    fprintf(arq, "%s", "Nomes dos alunos...\n");
    int i, j, k;
    for(i=0;i<3;i++){
        printf("Inf. o nome: ");
        fflush(stdin);
        fgets(inclusao[i].nome, 30, stdin);
        fprintf(arq, "%s",inclusao[i].nome);
        for(j=0;j<1;j++){
            for(k=0;k<4;k++){
                printf("Inf. as notas: ");
                fflush(stdin);
                fscanf(arq, "%d" ,&inclusao[i].notas[j][k]);
                fprintf(arq, "%d",inclusao[i].notas[j][k]);
            }
        }
    }

    fclose(arq);    
}

int menu(){//funcao para o menu do trabalho
    int escolha;
    printf("1) Limpar o conteudo do arquivo TXT\n");
    printf("2) Incluir conteudo do arquivo TXT\n");
    printf("3) Sair\n");
    printf("O que deseja fazer? ");
    scanf("%d",&escolha);
    int *ptr=&escolha;
    return *ptr;
}

int main(){ 
    setlocale(LC_ALL, "Portuguese");
    int menu1, contador_saida=0;
    char ch;

    LimpaTela();
    menu1 = menu();
    switch(menu1){
        case 2:
            LimpaTela();
            incluir(alunos);
        break;
    }
    printf("\nSaindo...\n");
    system("pause");
    return 0;
}

1 answer

0

You’re probably hoping that fflush(stdin) clear your input stream of any characters left in it from the last input, but the fflush was made to clean only outflow.

The behavior of fflush when it receives as a parameter an input stream is dependent on the implementation. Some implementations will clear an input stream as well, but this behavior is not portable and you should not rely on its existence.

Behold that answer for a solution to your problem that does not involve fflush(stdin).

Browser other questions tagged

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