0

I'm trying to create a char array in a similar way as using a printf statement.

If I do this:

printf("%d:%d:%.2f", hours, minutes, time);

It will print out exactly how I want it. However I'm now trying to store this as a variable. I've been trying to do something like the line of code below, however I get a "invalid initializer" error for char.

What I'm trying to do:

char temp[] = ("%d:%d:%.2f", hours, minutes, time);

I've also messed with strncat and couldn't figure that out either. Any guidance is appreciated!

CrusherW9
  • 3
  • 1
  • 3

4 Answers4

2

You'll want sprintf, it is the same as printf, but instead outputs to a string, as you wish.

EDIT: snprintf is indeed safer. (Thanks Troy)

Kninnug
  • 7,992
  • 1
  • 30
  • 42
1

You could use snprintf:

char temp[20];
snprintf(temp, sizeof(temp), "%d:%d:%.2f", hours, minutes, time);
LihO
  • 41,190
  • 11
  • 99
  • 167
1

you can use sprintf() or snprintf()

int sprintf( char *restrict buffer, const char *restrict format, ... );

int snprintf( char *restrict buffer, int buf_size,const char *restrict format, ... );

   char temp[30];
   sprintf(temp,"%d:%d:%.2f", hours, minutes, time);
   printf("%s\n",temp);    

For secure purpose use snprintf() as below

   char temp[30];
   snprintf(temp,sizeof temp,"%d:%d:%.2f", hours, minutes, time);
   printf("%s\n",temp);    
Gangadhar
  • 10,248
  • 3
  • 31
  • 50
  • 2
    I think it's worth pointing out that you should generally _never_ use `sprintf` (especially if any of the arguments are user-supplied or derived from data that's user-supplied). Using `sprintf`, if your formatted data ends up being larger than the buffer you passed it, the result will overflow into space outside the buffer, corrupting data and potentially causing crashes or (worse) a security vulnerability. `snprintf` avoids this by allowing you to specify the size of the buffer you passed it-- `snprintf` will never overflow its buffer. Best to get into good security practices early. – JonathonW Oct 05 '13 at 21:59
  • @JonathonW `never use sprintf (especially if any of the arguments are user-supplied or derived from data that's user-supplied)` Indeed info.Thanks for adding. – Gangadhar Oct 05 '13 at 22:07
  • Please leave comment when down voted my answer.some users are misusing down vote. – Gangadhar Oct 05 '13 at 22:26
0

You can use snprintf to do that. It is exacly what you need:

#include <cstdio>

char temp[50];
snprintf( temp, sizeof(temp), "%d:%d:%.2f", hours, minutes, time);
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62