【问题标题】:Convert double to wstring, but wstring must be formatted with scientific notation将double转换为wstring,但wstring必须用科学计数法格式化
【发布时间】: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


    【解决方案1】:

    您可以使用std::wstringstreamstd::scientific 标志来获取您正在寻找的输出作为wstring

    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <sstream>
    
    int main(int argc, char * argv[])
    {
        double val = 0.001500;
        std::wstringstream str;
        str << std::scientific << val;
        std::wcout << str.str() << std::endl;
        return 0;
    }
    

    您还可以使用附加输出标志设置浮点精度。查看reference page 了解更多您可以使用的输出操纵器。不幸的是,我不相信您的示例预期输出是可能的,因为正确的科学记数法是 1.5e-3

    【讨论】:

    • 再问一个问题:我必须为多个doubles 进行转换,我可以重复使用相同的wstringstream 而不是为每个操作创建一个新的吗?如果我可以重复使用wstringstream ,你能编辑你的答案来告诉我怎么做吗?感谢您的帮助。
    • 您需要在使用之间清除流,否则数字将一个接一个地附加到流中。有关如何执行此操作的详细信息,请参阅此 SO 问题:stackoverflow.com/questions/834622/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2011-01-03
    • 2018-01-14
    相关资源
    最近更新 更多