2

When I write a simple wprintf function and pass a double to it a float number using the verb notation L"%.2f" it simply prints an "f" on the screen instead of a number like in the format 0.00.

I would like some help as everywhere I look it simply says L"%.2f" is the way to print a number with 2 decimal digit precision.

float duration = (float)((std::clock() - mTimer) / (float)(CLOCKS_PER_SEC / 1000));
wsprintf(message, L">> Speed: %.2f\r\n", duration);

These are the 2 lines causing my headache... they result in

>> Speed: f

being printed on the console.

The output i'm looking for is this:

>> Speed: 4000.00
Stack Danny
  • 7,754
  • 2
  • 26
  • 55
Alice Turner
  • 81
  • 1
  • 9
  • What is `wsprintf()`? There's a `swprintf()` in the standard, but it takes different arguments... – Shawn Apr 17 '19 at 12:23
  • Ah, think I found it. [Some Windows thing](https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-wsprintfa)? Pay close attention to the documentation if so. – Shawn Apr 17 '19 at 12:27
  • Thank you i will also research this as i went with the `swprintf()` option in the end. But i will look in to the MSDN info you provided, i only code as a hobby so i'm not really trained or a professional lol. All the information i can get it much appreciated. Thank you Shawn – Alice Turner Apr 18 '19 at 09:16

2 Answers2

4

The function wsprintf() (which seems to be windows specific) does not support floating point parameters, You can go for swprintf() (which is a standard library function) instead.

Moreover, there is a note in the wsprintf documentation which states:

Do not use. Consider using one of the following functions instead: StringCbPrintf, StringCbPrintfEx, StringCchPrintf, or StringCchPrintfEx. See Security Considerations.

P.W
  • 26,289
  • 6
  • 39
  • 76
0

What you can do is :

cout << fixed << setprecision(2) << message << ">> Speed : "<< duration << endl;
Can Oezlemis
  • 169
  • 1
  • 10
  • Writing a logger, it's interface is generic pure virtual class but it's implementation it's platform specific. I'm writing the windows part now so i'm sticking to using all of the windows stuff and taking advantage of what Microsoft made specifically for their operating system but you might be right, using a stream might be the easier option – Alice Turner Apr 17 '19 at 12:33
  • Oh my bad, I did not figure out that you were trying to make a logger.... Should have paid more attention, my excuses . – Can Oezlemis Apr 17 '19 at 12:36