Program not to loop, even by typing the interrupt key!

Asked

Viewed 34 times

-1

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

typedef struct {
    int codigo;
    char departamento;
    char nome[30];
    float salario;
}DadosFuncionario;

int main () {
    FILE *fp;
    DadosFuncionario funcionario;
    char nome_arquivo[]= "saida.txt";
    char sair;

    fp = fopen(nome_arquivo, "w");


    do {
        printf("Codigo do Funcionario:\n");
        scanf("%d", &funcionario.codigo);

        printf("Departamento:\n");
        scanf(" %c", &funcionario.departamento);

        printf("Nome:\n");
        scanf(" %[^\n]s", funcionario.nome);

        printf("Salario:\n");
        scanf("%f", &funcionario.salario);

        fwrite(&funcionario, sizeof(DadosFuncionario),1,fp);

        printf("Deseja sair (s/S):");
        scanf("%c", &sair);

        }while(sair!= 's' && sair!='S');

        fclose(fp);
    return 0;
}
  • I believe you are having problem with ENTER character of the previous input that is not consumed and remains in the keyboard buffer. You can discard this ' n' with: while(exit = getchar()) != ' n' && exit != EOF) /* discards the read character */ ;. There are other ways to do it.

  • In a simpler way put a space before %c: scanf(" %c", &exit); the new line character will be consumed.

2 answers

0

Instead of being && no while, should be ||

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

typedef struct {
    int codigo;
    char departamento;
    char nome[30];
    float salario;
}DadosFuncionario;

int main () {
    FILE *fp;
    DadosFuncionario funcionario;
    char nome_arquivo[]= "saida.txt";
    char sair;

    fp = fopen(nome_arquivo, "w");


    do {
        printf("Codigo do Funcionario:\n");
        scanf("%d", &funcionario.codigo);

        printf("Departamento:\n");
        scanf(" %c", &funcionario.departamento);

        printf("Nome:\n");
        scanf(" %[^\n]s", funcionario.nome);

        printf("Salario:\n");
        scanf("%f", &funcionario.salario);

        fwrite(&funcionario, sizeof(DadosFuncionario),1,fp);

        printf("Deseja sair (s/S):");
        scanf("%c", &sair);

        }while(sair!= 's' || sair!='S');

        fclose(fp);
    return 0;
}
  • In this case just type either’s' or’S' which will continue running the loop. It has to be && same.

0

Put a space before %c

printf("Deseja sair (s/S):");
scanf(" %c", &sair);

Browser other questions tagged

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