我如何初始化动态分配的字符数组,所以我不会得到那些奇怪的字符?

Vai*_*los 2 c++

我想在我的"刽子手"游戏中使用那个字符数组来查看用户当前的进度.

#include <iostream>
#include "randword.h"
#include <fstream>
#include <time.h>
#include <cstdlib>

using namespace std;



int main()
{
InitDictionary();
string tixaio=Randomword();
int m = tixaio.length();
int guesses=8;
char *charptr= new char[m];





for(int aa=0;aa<m;aa++){
charptr[aa]='-';

}

cout << "The word now looks like this: "<<charptr;


}
Run Code Online (Sandbox Code Playgroud)

一旦我尝试cout << charptr我的数组我得到了通常的"---------"加上一些奇怪的字符.我该如何防止这些角色出现?

Nic*_*las 7

C和C++中的字符串必须以"\ 0"字符结尾:一个值为0的字符.

但是,您应该使用std::string而不是字符数组.然后你不必担心以空字符结尾.