How to solve string printing error?

Asked

Viewed 148 times

0

I’m passing a struct by reference to a function when entering the data, and again when printing this data. However the "Insert element" function does not read the time float (it skips the reading), and the "Print data" function does not print the strings on the screen only ints and floats.

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

typedef struct pessoa{
    char *nome;
    int idade;
    float salario;
    char *cargo;
    float tempo;

} PESSOA;
void Insere_elemento(PESSOA*dados);
void Imprime_dados(PESSOA*dados);
int main ()
{
    PESSOA dados;
    Insere_elemento(&dados);
    Imprime_dados(&dados);

    return 0;


}
void Insere_elemento(PESSOA*dados)
{
    char aux_nome[20];
    char aux_cargo[20];
    scanf("%[^\n]", aux_nome);
    dados->nome=aux_nome;
    __fpurge(stdin);
    scanf("%d", &dados->idade);
    scanf("%f", &dados->salario);
    scanf("%[^\n]", aux_cargo);
    dados->cargo=aux_cargo;
    __fpurge(stdin);
    scanf("%f", &dados->tempo);

}
void Imprime_dados(PESSOA*dados)
{
printf("%s \n", dados->nome);
printf("%d \n", dados->idade);
printf("%2.f \n", dados->salario);
printf("%s \n", dados->cargo);
printf("%2.f \n", dados->tempo);

}

1 answer

1

If you know how to control the readings and how they work, you don’t need to __fpurge nor similar.

In case it happens that reading with %[^\n] doesn’t work if the first thing that’s in the lobby is already a \n left by a foregoing %d or %f for example. There are countless ways around this problem but the simplest is to put a space before the %[^\n] to consume the previous break.

It is also wrong to use the char*, this:

void Insere_elemento(PESSOA*dados) {
    char aux_nome[20];
    scanf("%[^\n]", aux_nome);
    dados->nome=aux_nome;
    ...

This is wrong because the string for the name was allocated in the stack And when the space ends, the space will be marked as free, so any access you make afterwards represents undefined behavior. The solution is to allocate the direct characters with malloc and then read to the allocated space.

Example:

void Insere_elemento(PESSOA*dados) {
    dados->nome = malloc(20 * sizeof(char)); //alocação com malloc
    dados->cargo = malloc(20 * sizeof(char)); //alocação com malloc
    scanf("%[^\n]19s", dados->nome);
    scanf("%d", &dados->idade);
    scanf("%f", &dados->salario);
    scanf(" %[^\n]19s", dados->cargo);
    //     ^-- espaço consome a quebra anterior
    scanf("%f", &dados->tempo);
}

Note that the writing you are doing in Imprime_dados has the formatter %2.f when you probably wanted to %.2f

Look at the example I gave working on Ideone

Also note that I pushed the maximum reading size with scanf to 19 in order to avoid possible problems with buffer overflow.

Browser other questions tagged

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