Problem saving values to file . C-language CSV

Asked

Viewed 54 times

-1

Could someone please help me?

I am starting the study in the C language and I have the code below that receives values in the struct variables and writes in a file . CSV, until there is ok. The problem that is saving the value of the first variable in the first row and column of . CSV and other values in the second row (wrongly) and correct columns.

I looked for some alternatives but I haven’t found them here yet, what I’m trying to do is to have all user input values recorded all in the first row each in a column in the . CSV.

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

struct dados {
    char nome[46];
    char cpf[12];
    char telefone[12];
    char email[51];
}; struct dados registro[6];

int main() {

    char c;
    FILE *file = fopen("3346941.csv", "w");

    printf("REGISTRO DE DADOS: \n\n");

    // fprintf(file, "%s;%s;%s;%s", "Nome", "CPF", "Telefone", "Email");

    printf("Digite um nome: ");
    fgets(registro[0].nome, 45, stdin);
    while ((c = getchar()) != '\n' && c != EOF) {}

    printf("\nDigite um CPF (somente numeros): ");
    fgets(registro[1].cpf, 11, stdin);
    while ((c = getchar()) != '\n' && c != EOF) {}

    printf("\nDigite um telefone (somente numeros): ");
    fgets(registro[2].telefone, 11, stdin);
    while ((c = getchar()) != '\n' && c != EOF) {}

    printf("\nDigite um email: ");
    fgets(registro[3].email, 50, stdin);
    while ((c = getchar()) != '\n' && c != EOF) {}
    
    fprintf(file, "%s;%s;%s;%s", registro[0].nome, registro[1].cpf, registro[2].telefone, registro[3].email);
    fclose(file);

    return 0;
}

You’re saving it that way:

inserir a descrição da imagem aqui

I need it to stay that way but I haven’t been able to adjust yet:

inserir a descrição da imagem aqui

1 answer

0


I was able to solve the line breaking problem of the value of the first vector when it was going to the . CSV after some searching for the reason that was occurring this, identified that it was the last character that was going as a new line, it was necessary that I remove it from the string with the function strtok.

This way when the string is written to the file . CSV is on the same line as the other vectors in the way I was needing.

char *name_adjusted;

name_adjusted = register_data[0].name; 
strtok(name_adjusted, "\n"); 

Browser other questions tagged

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