intToStr recursively
intToStr recursively
本文关键字:recursively intToStr 更新时间:2023-10-16
这是学校的一个任务,我应该写一个递归函数,将给定的int转换为字符串,我知道我接近了,但我不能指出我的代码中缺失的东西,欢迎提示。
void intToStr(unsigned int num, char s[])
{
if (num < 10)
{
s[0] = '0' + num;
}
else
{
intToStr(num/10, s);
s[strlen(s)] = '0' + num%10;
}
}
编辑:我的问题是,该函数只适用于预初始化的数组,但如果我让函数工作在一个未初始化的函数,它将不起作用。
除非你的数组是零初始化的,否则你会在修改它时忘记添加空终止符。
把它加在最后一个字符后面:
void intToStr(unsigned int num, char s[])
{
if (num < 10)
{
s[0] = '0' + num;
s[1] = 0;
}
else
{
intToStr(num/10, s);
s[strlen(s)+1] = 0; //you have to do this operation here, before you overwrite the null terminator
s[strlen(s)] = '0' + num%10;
}
}
另外,你的函数假设s有足够的空间容纳所有的数字,所以你最好确保它(INT_MAX是10位数长我认为,所以你需要至少11个字符)。
Andrei Tita已经向您展示了NULL终止符的问题。我将向您展示另一种方法,以便您可以比较和对比不同的方法:
int intToStr(unsigned int num, char *s)
{
// We use this index to keep track of where, in the buffer, we
// need to output the current character. By default, we write
// at the first character.
int idx = 0;
// If the number we're printing is larger than 10 we recurse
// and use the returned index when we continue.
if(num > 9)
idx = intToStr(num / 10, s);
// Write our digit at the right position, and increment the
// position by one.
s[idx++] = '0' + (num %10);
// Write a terminating NULL character at the current position
// to ensure the string is always NULL-terminated.
s[idx] = 0;
// And return the current position in the string to whomever
// called us.
return idx;
}
您将注意到,我的alternative也返回它输出到缓冲区的字符串的最终长度。
祝你的课程顺利进行!