to_wstring().size() 的行为不符合预期

问题描述 投票:0回答:1

我有一个双变量,其内容需要转换为字符串。我需要计算该字符串最终会有多长,所以我尝试使用 size(),但这会导致意外的结果。

从此:

double test_double;
test_double = 12.34;
std::wstring test_string = L"12.34";
std::wcout << L"string is: " << test_string << std::endl;
std::wcout << L"length of string is: " << test_string.size() << std::endl; //this shows expected result
std::wcout << L"double is: " << test_double << std::endl;
std::wcout << L"length of double is: " << (std::to_wstring(test_double)).size() << std::endl; //and this makes me wonder

我得到这个输出:

string is: 12.34
length of string is: 5
double is: 12.34
length of double is: 9

字符串最终看起来是相同的,但由于某种原因转换的结果不同。我是不是错过了什么?

c++ wstring
1个回答
0
投票

std::to_wstring (https://en.cppreference.com/w/cpp/string/basic_string/to_wstring) 的文档指出它“将浮点值转换为宽字符串,就像通过

std::swprintf(buf, sz, L"%f", value)
”.

如果我们查看

swprintf
的文档 (https://en.cppreference.com/w/cpp/io/c/fwprintf) 并查看
f
格式说明符,我们会发现它默认为6 位精度。这导致字符串
12.340000

std::cout
将(默认)根据此处描述的
double
IO 操纵器格式化
defaultfloat
https://en.cppreference.com/w/cpp/io/manip/fixed。重要的是,您可以在他们的示例中看到它将截断零,从而在这种情况下产生
12.34

当您使用

std::to_wstring
显式转换为字符串时,您现在向
std::cout
提供显式字符串,因此它不会尝试为您聪明地截断。当您给出
std::cout
时,它必须决定显示数字的适当方式(固定数字、科学等)。事实证明,在这种情况下,默认行为似乎根本不是您想要的。

© www.soinside.com 2019 - 2024. All rights reserved.