C++将int转换为具有未知基的字符串的简单方法
C++ easy way to convert int to string with unknown base
以下是Java中的代码:
int a = 456;
int b = 5;
String s = Integer.toString(a, b);
System.out.println(s);
现在我想在C++中也一样,但我找到的所有转换都只转换为基数10。我不想用mysleft实现这一点,为什么要写一些已经存在的
尽管std::strtol
更灵活,但在受控情况下,您也可以使用itoa
。
int a = 456;
int b = 5;
char buffer[32];
itoa(a, buffer, b);
如果想要基数为8或16,则可以轻松使用字符串操纵器std::oct
和std::hex
。如果你想要任意基数,我建议你看看这个问题。
无错误处理http://ideone.com/nCj2XG:
char *toString(unsigned int value, unsigned int radix)
{
char digit[] = "0123456789ABCDEFGHIJKLMNOPRSTUVWXYZ";
char stack[32];
static char out[33];
int quot, rem;
int digits = 0;
do
{
quot = value / radix;
rem = value % radix;
stack[digits] = digit[rem];
value = quot;
digits++;
}
while( value );
int i = 0;
while(digits--)
{
out[i++] = stack[digits];
}
out[i] = 0;
return out;
}
没有标准函数itoa,它可以执行到任意微积分系统的转换。但例如,在我的编译器版本中没有实现。我的解决方案:
#include <string>
// maximum radix - base36
std::string int2string(unsigned int value, unsigned int radix) {
const char base36[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string result;
while (value > 0) {
unsigned int remainder = value % radix;
value /= radix;
result.insert(result.begin(), base36[remainder]);
}
return result;
}
相关文章:
- C++-字符串是否包含一个带有简单循环的单词
- 如何将\x00视为带有00(双零)的简单六边形字符串?
- boost::spirit::x3 中的简单字符串解析器不起作用
- 将字符从一个字符串简单分配到另一个字符串不起作用
- 为什么 for 循环只接受这个简单代码中的最后一个字符串?
- 简单的字符串替换给出错误,尽管参数正确
- 这个简单的 C++ 递归函数来反转字符串有什么问题?
- 在 c++ 中将简单的 xml 解析为字符串
- 有没有一种简单的方法可以将矢量 int 集转换为字符串输出?
- 在链接列表中添加字符串的简单方法
- 固定长度的最常见子字符串 - 需要简单的解决方案
- 有没有一种简单的方法可以从嵌入的 GNU ARM C++字符串中解析浮点数?
- C++简单的字符串程序
- 简单的游戏,同时循环和检查字符串
- 比较字符串大小写不区分的简单方法是什么?
- 一种在视图中用 ID 替换字符串的简单方法
- 你如何使字符串小写(简单的方法)?(C++)
- 有没有一种简单的方法可以将系统命令的输出转换为字符串
- 不同编译器版本的C++中的奇怪行为(字符串通过引用传递):参见简单的程序说明
- C字符串:简单问题