【问题标题】:C++ standard alternative to itoa() to convert int to base 10 char*itoa() 的 C++ 标准替代方案,用于将 int 转换为以 10 为底的 char*
【发布时间】:2013-11-17 18:31:25
【问题描述】:

将整数转换为以 10 为底的 char*

std::itoa(ConCounter, ID, 10);

ConCounter 为整数,ID 为 char*,10 为底数

它说 iota 不是 std 的成员,没有 std 它不会被声明。我知道这是一个非标准函数,但我包含了它的所有库,但它仍然看不到它。

有什么方法可以做到以上几点?有什么快速的一号线吗? 我尝试了以下方法;

std::to_string //it's not declared for me when using mingw, it doesn't exist.
snprintf/sprintf //should work but it gives me the "invalid conversion from 'int' to 'char *'"    error
std::stoi //has same problem as iota

【问题讨论】:

  • to_string 是 a) 在 C++11 中和 b) 在较新版本的 MinGW 中修复。
  • 顺便说一句,std::iota 与 itoa 完全不同。
  • @Chris 哪个新版本? This 不会在 MingW g++ (GCC) 4.8.1 上编译
  • @P0W,我似乎记得它已在主要版本中得到修复,但它绝对适用于 MinGWBuilds 4.8.1。

标签: c++ windows string int itoa


【解决方案1】:

试试这个:

#include <sstream>

int i = // your number
std::ostringstream digit;
digit<<i;
std::string numberString(digit.str());

【讨论】:

  • 我添加了这个,我得到一个“从 'constant char*' 到 'char*' 的无效转换”错误
  • 这是因为我删除了字符串部分,只是做了 ID = digit.str().c_str();这就是我收到错误的原因。
【解决方案2】:

我建议使用 roybatty 的答案,但我认为 sprintf 也应该可以。我认为当您使用它时,您忘记了格式字符串。应该是:

char buf[16];
std::snprintf(buf, sizeof(buf), "%d", integer);

【讨论】:

  • 我所看到的所有地方都没有被告知“sizeof(--)”部分。似乎这部分使它起作用。谢谢!
  • @nurtul 如果你使用snprintf,你需要它,如果你使用sprintf,你不需要。
【解决方案3】:

【讨论】:

  • strol 与预期相反
  • 哦,对不起 %) A 认为它是问题中的“atoi”。
猜你喜欢
  • 2012-02-04
  • 2013-06-12
  • 1970-01-01
  • 2014-12-28
  • 2016-11-29
  • 1970-01-01
  • 2015-12-18
  • 2015-01-29
  • 1970-01-01
相关资源
最近更新 更多