I've implemented a to_string
function that takes a player_t
instance and format it into a string.
Code:
#include <stdio.h>
#include <string.h>
typedef struct player {
int id;
float points;
char display_name[256];
} player_t;
#define MAX_OUTPUT_SIZE sizeof(int) + sizeof(float) + 256
void to_string(player_t, char [MAX_OUTPUT_SIZE]);
int main()
{
char stringified[MAX_OUTPUT_SIZE];
player_t p1 = {.id = 1, .points = 17.4, .display_name = "Tester"};
to_string(p1, stringified);
printf("player: %s\n", stringified);
return 0;
}
void to_string(player_t player, char output[MAX_OUTPUT_SIZE])
{
char temp[MAX_OUTPUT_SIZE];
snprintf(temp, sizeof(temp), "\n\tid: %d", player.id);
strncat(output, temp, 6 + 1);
snprintf(temp, sizeof(temp), "\n\tpoints: %f", player.points);
strncat(output, temp, 10 + 9);
snprintf(temp, sizeof(temp), "\n\tdisplay_name: %s", player.display_name);
strncat(output, temp, 18 + 256);
}
Output:
player:
id: 1
points: 17.400000
display_name: Tester
Questions:
- Is there a better way to define
MAX_OUTPUT_SIZE
instead of manually adding the size of each element? - Is there a better way to implement
to_string
instead of using a temporary variable, the separate combination ofstrncat
&snprintf
and explicitly counting the characters forstrncat
?. - Am I over complicating my usage of
snprintf
&strncat
? - (slightly out of topic) Do you recommend any C project to read it's code that implement similar functionalities and is following best practices?
Thanks in advance and I'm sorry if I've missed any obvious mistakes (still in the process of learning C with Ruby/JS background).