在 C 中将 int 转换为字符串的最简单方法

新手上路,请多包涵

在 C++ 中从 int 转换为等效 string 的最简单方法是什么?我知道两种方法。有没有更简单的方法?

(1)

 int a = 10;
char *intStr = itoa(a);
string str = string(intStr);

(2)

 int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

原文由 Nemo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 646
2 个回答

C++11 introduces std::stoi (and variants for each numeric type) and std::to_string , the counterparts of the C atoi and itoa but用 std::string 表示。

 #include <string>

std::string s = std::to_string(42);

因此是我能想到的最短的方法。您甚至可以省略命名类型,使用 auto 关键字:

 auto s = std::to_string(42);

注意:参见 [string.conversions]n3242 中的 21.5

原文由 Matthieu M. 发布,翻译遵循 CC BY-SA 3.0 许可协议

您所要做的就是在定义变量时使用 StringString intStr )。每当您需要该变量时,请调用 whateverFunction(intStr.toInt())

原文由 merpcode 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题