【发布时间】:2015-11-26 22:59:18
【问题描述】:
我有一个double,格式为xxxxx.yyyy,例如0.001500。
我想把它转换成wstring,用科学记数法格式化。这是我想要的结果:0.15e-2。
我对 C++ 没有那么丰富的经验,所以我检查了std::wstring reference 并没有找到任何可以做到这一点的成员函数。
我在 Stack Overflow 上找到了 similar threads,但我只是不知道如何应用这些答案来解决我的问题,尤其是因为他们不使用 wchar。
我已经尝试自己解决这个问题:
// get the value from database as double
double d = // this would give 0.5
// I do not know how determine proper size to hold the converted number
// so I hardcoded 4 here, so I can provide an example that demonstrates the issue
int len = 3 + 1; // + 1 for terminating null character
wchar_t *txt = new wchar_t[3 + 1];
memset(txt, L'\0', sizeof(txt));
swprintf_s(txt, 4, L"%e", d);
delete[] txt;
我只是不知道如何分配足够大的缓冲区来保存转换结果。每次我得到缓冲区溢出时,这里的所有答案都来自类似线程 estimate 的大小。我真的很想避免这种引入“神奇”数字的方式。
我也不知道如何使用stringstream,因为这些答案没有将double 转换为wstring 科学符号。
我只想将double 转换为wstring,然后将wstring 格式化为科学计数法。
【问题讨论】:
标签: c++ double string-formatting wstring