char数组包含荒谬的字符 [英] char array contains absurd characters
问题描述
void eatSpaces(const char arr[])
{
char* str = new char[];
size_t strPosition{}, arrPosition{};
while (arr[arrPosition] != '\0')
{
if (arr[arrPosition] != ' ')
str[strPosition++] = arr[arrPosition];
arrPosition++;
}
cout << str << endl;
}
void main()
{
char str[]{"hello world"};
eatSpaces(str);
}
每次运行此程序时,它会在str []结尾显示2个荒谬的字符。它们就像一些随机生成的角色..
这是第一次显示helloworldφ8
然后, helloworld .C
之后,helloworld├b
不是同样总是..我只是想知道为什么会发生这种情况..没有另一种方法来删除没有这个问题的空间..谢谢..
every time I run this program it shows 2 absurd characters at the end of the str[]. They are like some randomly generated characters..
For the first time, it displays "helloworldφ8"
and then, "helloworld.C"
after that, "helloworld├b"
It isn't same always.. I just want to know why this happens.. Not another way to remove spaces without this problem.. Thanks..
推荐答案
问题是你将字符从arr
复制到str
,并在到达空字符时停止(正确)。但是,您忘记在新创建的字符串的末尾添加空字符。它应该是:
The problem is that you copy the characters fromarr
tostr
, and stop (correctly) when the null character is reached. However, you forget to add a null character at the end of the newly created string. It should be:
while (arr[arrPosition] != '\0')
{
if (arr[arrPosition] != ' ')
str[strPosition++] = arr[arrPosition];
arrPosition++;
}
str[strPosition] = '\0'; // null terminate the new string
顺便说一下,你使用的是什么编译器,因为在某些语句中有一些奇怪的语法,因此无法在Microsoft的C ++编译器下编译?
By the way, what compiler are you using, as this will not compile under Microsoft's C++ compiler, owing to the strange syntax on some statments?
这篇关于char数组包含荒谬的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!