【问题标题】:Convert wchar_t to float in c++在 c++ 中将 wchar_t 转换为浮点数
【发布时间】:2014-03-23 19:03:16
【问题描述】:

有没有更好的方法将 wchar_t 转换为浮点数?我只找到了一种真正有效的解决方案。

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

我也尝试了以下失败:

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

float fNumber1 = _wtof(&GetText();

float fNumber1 = _wtof(&(GetText())); 

【问题讨论】:

  • 你可能应该空终止它。不能保证第一个完全有效的事实。如:wchar_t buf[] = {GetText(), 0};
  • std::stof 效果很好。
  • 我不敢相信 有效。有人应该认真地考虑将该函数重命名为GetWChar(),因为它似乎就是这样做的。其次,函数_wtof() 解释字符,直到遇到不符合double 的字符,然后停止(包括在nullchar 上停止)。由于您的“字符串”中没有 nullchar(因为它不是字符串),因此 doesn't 调用 UB 的唯一方法是在第一个也是唯一的 failing char 已处理。

标签: c++ typeconverter wchar-t


【解决方案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;
}

【讨论】:

  • 虽然纯代码答案可能会回答问题,但最好在答案中留下一些文字来解释为什么/如何解决问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-08
相关资源
最近更新 更多