0

I'm confused because I thought the sprintf function returned a string, and it shows on cplusplus.com that it returns an int? Why?

Basically, I'm having trouble with the following line, where I'm trying to pad some spacing and format a string simultaneously:

printf("%30s", sprintf("1.10f", modeTimeTotal/num_tests));

There error I get is:

cannot convert 'double' to 'const char*' for argument '2' to 'int sprintf(char*, const char*, ...)'
Codes with Hammer
  • 808
  • 2
  • 15
  • 46

2 Answers2

5

sprintf prints into a string an returns the number of characters so printed. The first argument to the sprintf call should be the string to print into:

char buffer[30];
int n = sprintf(buffer, "%1.10f", modeTimeTotal/num_tests);
printf("Printed %d characters.  String is '%s'\n", n, buffer);

You're getting the warning you are because you're trying to shoehorn the modeTimeTotal/num_tests into the format string argument to sprintf.

Carl Norum
  • 201,810
  • 27
  • 390
  • 454
0

sprintf() returns the number of characters printed (not including the NUL terminator byte).

You should use it like this:

char buf[512];
sprintf(buf, "%30s%1.10f", "", modeTimeTotal/num_tests);
printf("%s\n", buf);
Jeremy Friesner
  • 57,675
  • 12
  • 103
  • 196
  • [sprintf](http://www.cplusplus.com/reference/cstdio/sprintf/) "Return Value On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string. On failure, a negative number is returned." – Jongware Sep 12 '13 at 15:12