Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C打印字符串会产生奇怪的字符_C++ - Fatal编程技术网

C++ C打印字符串会产生奇怪的字符

C++ C打印字符串会产生奇怪的字符,c++,C++,我试图通过以下方式输出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&

我试图通过以下方式输出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来尝试这个函数,我得到了。我做错了什么?

您正在访问下一行中超出数组边界的内容

string[lengthOfInt--] = ch;
这会尝试访问不正确的索引
lengthofInt

现在,忽略带有变量的数组声明

char string[lengthOfInt];
声明一个数组,该数组的索引从
0
lengthofInt-1


此外,根据您打印字符串的方式,您可能需要在末尾使用“\0”字符。尽管如此,如果您要逐个字符地进行,并且确定自己的边界,则不需要,但还是建议您这样做。

C中的所有字符串都必须以nul字节(0)结尾。因此,首先在堆栈上分配的字符数组长度中添加1,然后在打印之前将nul字节添加到字符串中


我想这是一个家庭作业。否则,您应该只使用
itoa
函数。

忽略以下事实:您正在使用变量(您应该使用动态分配或至少是常量)声明数组,
char string[lengthOfInt]需要是
字符字符串[lengthOfInt+1]string[lengthOfInt]='\0'在while循环之前。C字符串以NULL结尾


另外,为什么不干脆
printf(“%d”,i)

加入21世纪,使用
std::string

首先,
函数
是函数名称的可怕选择。你想用这段代码实现什么?可能需要看看“函数”是如何工作的。您是否尝试在数组中分配额外的字符并以null终止(将最后一个值设置为“\0”)?不确定从何处开始。为什么不做一个printf呢?字符串数组从来没有初始化过,所以一开始就填充了垃圾。你知道itoa函数吗?-1:不,肯定没有。C++没有VLA.@非停止旅行,我不明白你想指出什么。用变量来声明一个数组,例如,代码> char string [trangthoftI] < /Cord>是GCC扩展,并且不受标准支持。@ AddundSon OK,那么我的答案在哪里出错?@ ASHRJ:我指出你的答案是错误的。- 1,它的作业分配和操作是使用C不C++ + Ri硬实码OP标记它的C++。@不停止,UR修正和我删除- 1。在我的辩护中,标题称C不是C++。