How to resolve error in printing strings?

0

I'm passing a struct by reference to a function at the time of inserting the data, and again at the time of printing this data. But the "insert_element" function does not read the time float (it skips the reading), and the function "Print_dates" does not print the strings on the screen just the 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);

}
    
asked by anonymous 07.11.2018 / 12:15

1 answer

1

If you know how to control the readings and how they work, you do not need __fpurge or similar.

In this case, reading with %[^\n] does not work if the first thing that is in the input is already a \n left by a previous %d or %f for example. There are a number of ways to get around this problem, but the simplest thing is to put a space before %[^\n] to consume the previous break.

You're also wrong about what you're doing with char* , this:

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

It is wrong because the string for the name was allocated to the function in stack and when it is finished the space will be marked as free and so any access it does afterwards represents undefined behavior. The workaround is to allocate the characters directly 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 %2.f formatter when you probably wanted %.2f

See the example I gave Ideone

Also note that I forced the maximum size in the read with scanf to 19 to avoid possible problems with buffer overflow .

    
07.11.2018 / 12:55