我试图以下列方式输出一个int:
void the_int(int i)
{
int lenghtOfInt = 0;
int tempValue = i;
while(tempValue >= 1)
{
tempValue/=10;
lenghtOfInt++;
}
int currentDigit;
char string[lengthOfInt];
while(i>9)
{
currentDigit= i % 10;
i = i/10;
char ch = (char)(((int)'0')+currentDigit);
string[lengthOfInt--] = ch;
}
string[lengthOfInt]= (char)(((int)'0')+i);
function(str); //prints the string character by character
}
如果我在i = 12的情况下尝试这个功能,我会得到à12ç。我做错了什么?
答案 0 :(得分:3)
加入21世纪并使用std::string
。
答案 1 :(得分:1)
您正在访问以下行中的数组范围之外。
string[lengthOfInt--] = ch;
这会尝试访问不正确的索引lengthofInt
。
现在,忽略带变量的数组声明
char string[lengthOfInt];
声明一个索引从0
到lengthofInt - 1
此外,根据您打印字符串的方式,最后可能需要一个'\ 0'字符。虽然,如果你逐字逐句,并确定你的界限,那么它是不需要的,但仍然是推荐的。
答案 2 :(得分:1)
C中的所有字符串必须以nul字节(0)结尾。所以首先在堆栈上分配的char数组的长度加1,然后在打印之前将nul字节添加到字符串中。
我认为这是一项家庭作业。否则,您应该只使用itoa
函数。
答案 3 :(得分:1)
忽略您使用变量声明数组的事实(您应该使用动态分配或至少是常量),char string[lengthOfInt];
需要char string[lengthOfInt+1];
,并且您需要string[lengthOfInt] = '\0';
在while循环之前。 C字符串以NULL结尾。
此外,为什么不只是printf("%d", i);
?