How can I add a variable inside a string using the C language?

Asked

Viewed 51 times

1

In my code, I need to insert within an SQL statement the date formatted as a string using this format:

14/06/2020 - 20h40

But I get the values (minutes, hours, days, months, years) separately (a value in each variable).

How can I insert these variables into the string in this way:

char *sql = "INSERT INTO register VALUES('Luis', '<dia>/<mes>/<ano> - <horas>h<minutos>');";

If it is not possible to insert a variable in this way, is there an alternative?

  • 2

    You can use the function sprintfto generate the desired string. sprintf(sql, "INSERT INTO register VALUES('Luis', '%.2d/%.2d/%.4 - %.2dh%.2d');", dia, mes, ano, horas, minutos);. Don’t forget to reserve space for the string.

  • @anonimo It would be better to put this comment as a response.

1 answer

1


Doubt answered with the anonymous comment below my post, thank you!

sprintf(sql, "INSERT INTO register VALUES('Luis', '%.2d/%.2d/%.4 - %.2dh%.2d');", dia, mes, ano, horas, minutos);

Browser other questions tagged

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