【发布时间】: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