我需要将双精度存储为字符串。我知道我可以使用 printf
如果我想显示它,但我只想将它存储在一个字符串变量中,以便以后可以将它存储在地图中(作为 value ,而不是 key )。
原文由 Bill the Lizard 发布,翻译遵循 CC BY-SA 4.0 许可协议
我需要将双精度存储为字符串。我知道我可以使用 printf
如果我想显示它,但我只想将它存储在一个字符串变量中,以便以后可以将它存储在地图中(作为 value ,而不是 key )。
原文由 Bill the Lizard 发布,翻译遵循 CC BY-SA 4.0 许可协议
C++17 引入了: std::to_chars、std::to_chars_result - cppreference.com
std::to_chars_result to_chars( char* first, char* last, float value, std::chars_format fmt, int precision ); std::to_chars_result to_chars( char* first, char* last, double value, std::chars_format fmt, int precision ); std::to_chars_result to_chars( char* first, char* last, long double value, std::chars_format fmt, int precision );
它提供了快速的低级方法来将浮点数转换为具有某种级别格式控制的字符串。这应该很快,因为没有完成分配,只有特定场景的自定义实现应该更快。
C++20 引入了高级易用的格式字符串(相当于 fmt 库):
std::format - cppreference.com
标准::格式
template< class... Args > std::string format( /*format_string<Args...>*/ fmt, Args&&... args ); template< class... Args > std::wstring format( /*wformat_string<Args...>*/ fmt, Args&&... args ); template< class... Args > std::string format( const std::locale& loc, /*format_string<Args...>*/ fmt, Args&&... args ); template< class... Args > std::wstring format( const std::locale& loc, /*wformat_string<Args...>*/ fmt, Args&&... args );
这是非常好的和方便的。应该比 sprintf
更快。
原文由 Marek R 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答2.7k 阅读✓ 已解决
升压(tm) 方式:
标准 C++ 方式:
注意:不要忘记
#include <sstream>