繁体   English   中英

在 C++ 中将浮点数转换为 std::string

[英]Convert float to std::string in C++

我有一个需要放入std::string的浮点值。 如何从浮点数转换为字符串?

float val = 2.5;
std::string my_val = val; // error here

从 C++11 开始,标准 C++ 库为函数std::to_string(arg)提供了各种支持的arg类型。

除非您担心性能,否则请使用字符串流

#include <sstream>
//..

std::ostringstream ss;
ss << myFloat;
std::string s(ss.str());

如果你对 Boost 没问题, lexical_cast<>是一个方便的选择:

std::string s = boost::lexical_cast<std::string>(myFloat);

有效的替代方法是例如FastFormat或简单的 C 样式函数。

重要
阅读最后的注释。

快速回答 :
使用to_string() (自 c++11 起可用)
例子 :

#include <iostream>   
#include <string>  

using namespace std;
int main ()
{
    string pi = "pi is " + to_string(3.1415926);
    cout<< "pi = "<< pi << endl;

  return 0;
}

自己运行: http : //ideone.com/7ejfaU
这些也可用:

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

重要的提示:
正如@Michael Konečný 正确指出的那样,使用to_string()充其量是有风险的,因为它很可能会导致意外结果。
http://en.cppreference.com/w/cpp/string/basic_string/to_string

对于浮点类型std::to_string可能会产生意外的结果,因为返回的字符串中的有效位数可能为零,请参见示例。
返回值可能与std::cout默认打印的显着不同,请参见示例。 std::to_string依赖当前语言环境进行格式化,因此从多个线程并发调用std::to_string可能导致调用的部分序列化。 C++17提供std::to_chars作为更高性能的语言环境独立替代方案。

最好的方法是使用stringstream作为其他人,例如 @dcp 在他的回答中展示的。:

以下示例演示了此问题:
自己运行示例: https : //www.jdoodle.com/embed/v0/T4k

#include <iostream>
#include <sstream>
#include <string>

template < typename Type > std::string to_str (const Type & t)
{
  std::ostringstream os;
  os << t;
  return os.str ();
}

int main ()
{

  // more info : https://en.cppreference.com/w/cpp/string/basic_string/to_string
  double    f = 23.43;
  double    f2 = 1e-9;
  double    f3 = 1e40;
  double    f4 = 1e-40;
  double    f5 = 123456789;
  std::string f_str = std::to_string (f);
  std::string f_str2 = std::to_string (f2); // Note: returns "0.000000"
  std::string f_str3 = std::to_string (f3); // Note: Does not return "1e+40".
  std::string f_str4 = std::to_string (f4); // Note: returns "0.000000"
  std::string f_str5 = std::to_string (f5);

  std::cout << "std::cout: " << f << '\n'
    << "to_string: " << f_str << '\n'
    << "ostringstream: " << to_str (f) << "\n\n"
    << "std::cout: " << f2 << '\n'
    << "to_string: " << f_str2 << '\n'
    << "ostringstream: " << to_str (f2) << "\n\n"
    << "std::cout: " << f3 << '\n'
    << "to_string: " << f_str3 << '\n'
    << "ostringstream: " << to_str (f3) << "\n\n"
    << "std::cout: " << f4 << '\n'
    << "to_string: " << f_str4 << '\n'
    << "ostringstream: " << to_str (f4) << "\n\n"
    << "std::cout: " << f5 << '\n'
    << "to_string: " << f_str5 << '\n'
    << "ostringstream: " << to_str (f5) << '\n';

  return 0;
}

输出 :

std::cout: 23.43
to_string: 23.430000
ostringstream: 23.43

std::cout: 1e-09
to_string: 0.000000
ostringstream: 1e-09

std::cout: 1e+40
to_string: 10000000000000000303786028427003666890752.000000
ostringstream: 1e+40

std::cout: 1e-40
to_string: 0.000000
ostringstream: 1e-40

std::cout: 1.23457e+08
to_string: 123456789.000000
ostringstream: 1.23457e+08 

您可以定义一个模板,它不仅适用于双打,也适用于其他类型。

template <typename T> string tostr(const T& t) { 
   ostringstream os; 
   os<<t; 
   return os.str(); 
} 

然后你可以将它用于其他类型。

double x = 14.4;
int y = 21;

string sx = tostr(x);
string sy = tostr(y);

一旦您的标准库提供std::to_chars ,请使用它:

std::array<char, 32> buf;
auto result = std::to_chars(buf.data(), buf.data() + buf.size(), val);
if (result.ec == std::errc()) {
  auto str = std::string(buf.data(), result.ptr - buf.data());
  // use the string
} else {
  // handle the error
}

这种方法的优点是:

  • 它与语言环境无关,可以防止在将数据写入需要 '.' 的 JSON 等格式时出现错误。 作为小数点
  • 它提供最短的十进制表示和往返保证
  • 它可能比其他标准方法更有效,因为它不使用语言环境并且不需要分配

不幸的是std::to_string对浮点的效用有限,因为它使用固定表示,将小值四舍五入为零并为大值生成长字符串,例如

auto s1 = std::to_string(1e+40);
// s1 == 10000000000000000303786028427003666890752.000000

auto s2 = std::to_string(1e-40);
// s2 == 0.000000

如果P0645标准提案获得批准,C++20 可能会获得更方便的std::format API,其优点与std::to_chars to_chars相同。

您可以在 C++11 中使用std::to_string

float val = 2.5;
std::string my_val = std::to_string(val);

如果您担心性能,请查看Boost::lexical_cast库。

本教程提供了一个简单而优雅的解决方案,我将其转录为:

#include <sstream>
#include <string>
#include <stdexcept>

class BadConversion : public std::runtime_error {
public:
  BadConversion(std::string const& s)
    : std::runtime_error(s)
    { }
};

inline std::string stringify(double x)
{
  std::ostringstream o;
  if (!(o << x))
    throw BadConversion("stringify(double)");
  return o.str();
}
...
std::string my_val = stringify(val);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM