0
Good guys, I am developing a C code that performs data registration in files. However, I have a problem in the function register, which you will see below among the codes.
Struct of the client:
typedef struct
{
int idCliente;
char nome[NOME_TAM_MAX];
char CPF[16];
char endereco[ENDERECO_TAM_MAX];
}Cliente;
Macros:
#define NOME_TAM_MAX 51
#define ENDERECO_TAM_MAX 101
Function register:
void cadastrarCliente (void)
{
Cliente *newCliente = (Cliente *) malloc(sizeof(Cliente));
if (!newCliente)
{
printf("ERRO DE MEMORIA!!!\n");
exit(-1);
}
else
{
printf("\n--- PRENCHA OS DADOS DE CADASTRO DO CLIENTE ---\n\n");
printf("Digite o ID do cliente: ");
scanf(" %d", &newCliente->idCliente);
printf("Digite o nome do cliente: ");
scanf(" %s", newCliente->nome);
printf("Digite o CPF do cliente: ");
scanf(" %s", newCliente->CPF);
printf("Digite o endereco do cliente: ");
scanf(" %s", newCliente->endereco);
stream = fopen("cliente.txt", "w+b"); // stream é global
if (!stream)
{
fputs("ERRO AO TENTAR LER ARQUIVO!!!\n", stderr);
exit(-1);
}
else
{
fwrite(newCliente, sizeof(Cliente), 1, stream);
fclose(stream);
}
}
return;
}
The error is as follows, after typing the client name and hit enter, all other attributes are skipped (showing only the contents of the printf) and the function comes to an end. I inverted the fields, putting the CPF first and then address, after reading the CPF, everything happens successful, but the error repeats when reading the address as well.
The name you are putting has spaces ? Remember that
scanf("%s
reads only one word, leaving the rest in the input stream. If you want to read an entire line, switch toscanf("%[^\n]
– Isac
It does have spaces, but I thought that this problem could be solved by giving a spacing inside the scanf, as it is in the code. I tried to use it as you suggested, but it doesn’t work.
– Yuri Coelho
Give an example of the input type you are reading, to be able to say the appropriate way to read it
– Isac
Yuri Coelho Rosario
– Yuri Coelho
Each of these would be placed at a time separated by enter ? Or would seperation be by the commas ? Your code interprets 1 number followed by 3 texts. I don’t see how this fits in the example you gave
– Isac
The separation would be through enter, after enter, passes to the next. In this case, the first entry is any number, the second the full name, the third the CPF and the fourth the full address.
– Yuri Coelho