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!

2
  • 1
    You are looking for sprintf Commented Oct 5, 2013 at 21:15
  • 1
    I just don't understand C++ tag. This seems to be C. Commented Oct 5, 2013 at 21:19

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

snprintf would be a safer bet.
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);    

3 Comments

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 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.
Please leave comment when down voted my answer.some users are misusing down vote.
1

You could use snprintf:

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

1 Comment

20 => sizeof temp
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);

1 Comment

50 => sizeof temp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.