Convert structure to string

Asked

Viewed 108 times

0

How do I convert an integer to string? Example: convert int cod for char cod[30].

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <windows.h>



struct Tipo_Lista{
    int cod;
    struct Tipo_Lista *Prox;
};

struct Tipo_Lista *Primeiro;
struct Tipo_Lista *Ultimo;

void FlVazia(){
    struct Tipo_Lista *aux;
    aux = (struct Tipo_Lista*)malloc(sizeof(struct Tipo_Lista));
    Primeiro = aux;
    Ultimo = Primeiro;
}

int Insere(int x){
    struct Tipo_Lista *aux;
    aux = (struct Tipo_Lista*)malloc(sizeof(struct Tipo_Lista));
    aux->cod = x;
    Ultimo->Prox = aux;
    Ultimo = Ultimo->Prox;
    aux->Prox = NULL;
}

void Imprime(){
    struct Tipo_Lista *aux;
    aux = Primeiro->Prox;
    while(aux !=NULL){
        printf("\n\nItem = %d", aux->cod);
        aux = aux->Prox;
    }
}
  • You’re wanting the contents of an entire to turn into a string?

1 answer

1

If you have an integer and want to turn it into a string, you can use the function sprintf which does the opposite of atoi.

The function sprintf

int sprintf(char *str, const char *format, ...);

creates a string with the same content to be printed if format was used in printf, but instead of printing, the content is stored in a buffer pointed by str.

The buffer pointed by str must be large enough to store the resulting string.

Read more about this function here.

I mean, what you want to do is:

int numero = 20180815;
char palavra[100];
sprintf(palavra, "%d", numero);
// Agora, palavra tem como conteudo "20180815".
  • Interesting, I had never really seen this function must have an sscanf too right, but like for me to put this in my Inserts function. I was trying to do something and it didn’t work out like. int sprintf(char *x){

Browser other questions tagged

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