C++ intToStr递归
这是学校的一项任务,我应该写一个递归函数,将给定的int转换成字符串,我知道我很接近,但我不能指出代码中缺少的东西,欢迎提供提示C++ intToStr递归,c++,c,arrays,recursion,C++,C,Arrays,Recursion,这是学校的一项任务,我应该写一个递归函数,将给定的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%1
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[])
{
如果(数值<10)
{
s[0]=“0”+num;
}
其他的
{
intToStr(数量/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;
}
}
void intToStr(unsigned int num,char s[])
{
if(num<10)
{
s[0]=“0”+num;
s[1]=0;
}
其他的
{
intToStr(数量/10,s);
s[strlen(s)+1]=0;//在覆盖空终止符之前,必须在此处执行此操作
s[strlen(s)]=“0”+num%10;
}
}
此外,您的函数假设s有足够的空间容纳所有数字,因此您最好确保它有足够的空间(我认为INT_MAX是10个数字,因此您至少需要11个字符)。Andrei Tita已经向您展示了空终止符的问题。我将向您展示一个备选方案,以便您可以比较和对比不同的方法:
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;
}
您会注意到,我的替代方案还返回它输出到缓冲区的字符串的最终长度
祝你的课程顺利进行 如果您描述哪些代码不起作用,也许会有帮助?[s是如何初始化的?]这正是问题所在,当s被初始化时,一切都工作得很好,但是如果s没有被赋予函数初始化的话,事情就会变得一团糟。我知道这与我没有将\0放在字符串末尾有关,但我不知道应该将它放在哪里。“\0”和0(为此目的)是一样的。我可以假设数组足够大