char数组包含荒谬的字符 [英] char array contains absurd characters

查看:66
本文介绍了char数组包含荒谬的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 from arr to str, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆