2

Is there a better way to convert a wchar_t to float? I've only found one solution that actually works.

wchar_t buf = GetText(); // GetText() returns a wchar_t
float fNumber1 = _wtof(&buf);

I've tried the following as well that fail:

float fNumber1 = (float)GetText(); // returns the ascii code

float fNumber1 = _wtof(&GetText();

float fNumber1 = _wtof(&(GetText())); 
Vince
  • 2,596
  • 11
  • 43
  • 76
  • You probably ought to null-terminate that. The fact that the first one works at all is not guaranteed. As in: `wchar_t buf[] = {GetText(), 0};` – Cornstalks Feb 22 '14 at 01:34
  • 1
    `std::stof` works pretty well. – chris Feb 22 '14 at 01:34
  • 1
    I can't believe *that* works. Someone should *seriously* consider renaming that function to `GetWChar()` because thats all it appears to do. Secondly the function `_wtof()` interprets characters until one that is non-conforming to a `double` is encounterd, then stops (including stopping on nullchar). Since there is no nullchar in your "string" (because it isn't a string) the only way this *doesn't* invoke UB is by *failing* on the first and only char processed. – WhozCraig Feb 22 '14 at 01:39

1 Answers1

1
#include <wchar.h>

int main ()
{
  wchar_t szOrbits[] = L"90613.305 365.24";
  wchar_t * pEnd;
  long double f1, f2;
  f1 = wcstold (szOrbits,&pEnd);
  f2 = wcstold (pEnd,NULL);
  wprintf (L"Pluto takes %.2Lf years to complete an orbit.\n", f1/f2);
  return 0;
}
SaeidMo7
  • 1,214
  • 15
  • 22
  • 1
    While code-only answers can potentially answer the question, it is better to leave some text in the answer to explain why/how this solves the question. – Jonathan Aug 31 '17 at 02:05