首页 > 解决方案 > 我可以在不包含任何库的情况下将 int 转换为字符串吗??

问题描述

我可以在没有任何库的情况下将“int”转换为“string”<iostream>吗?这个'int'包括否定的情况。

标签: c++type-conversion

解决方案


我可以在没有任何库的情况下将“int”转换为“string”吗?

如果你的意思是:

除了已经用 C++ 构建的库

然后看:to_string

例子:

// to_string example
#include <iostream>   // std::cout
#include <string>     // std::string, std::to_string

int main ()
{
  std::string pi = "pi is " + std::to_string(3.1415926);
  std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
  std::cout << pi << '\n';
  std::cout << perfect << '\n';
  return 0;
}

输出:

pi is 3.141593
28 is a perfect number

推荐阅读