C++中 ToString( "00" ) 的等价物是什么?

What is the equivalent of ToString("00") in C++?

本文关键字:等价物 是什么 ToString C++      更新时间:2023-10-16

C++中.ToString("00")的等价物是什么?

我收到一个错误,说明

left of '.ToString' must have class/struct/union
1>        type is 'double'

更新:谢谢你的回复,我现在有另一个类似的问题//为了得到//.ToString("00.00000"),我做了以下

  memset(buf, 0, sizeof(buf));
  sprintf_s(buf, "%02.7f",latm); //.7 to match heremisphere
  std::string latm_str = buf;

我意识到%02没有任何影响,例如,当我得到7.0时,结果是7.0000000,而不是期望的07.0000000,这里有什么错吗?

我认为您应该使用std::to_string

double number = 3.14;
char buf[100];
sprintf_s(buf, "%02d", (int)number);
string s = buf;
cout << s; // prints 03

基于自定义字符串格式:ToString("00")

我猜这是基于这个链接的C#。如果是这样的话,取决于您是否可以访问C++11,您可能可以使用以下内容:

int a = 3;
std::string s = std::to_string(a);

如果你还没有使用C++11,那么你可以使用以下工具:

int a = 3;
std::ostringstream ss;
ss.fill('0');
ss << std::setw(2) << a;
std::string s = ss.str();

更多的细节是关于这个问题

您正在寻找C++中的std::to_string

double abc = 23.233;
std::string mystring = std::to_string(abc);