一个奇怪的字符出现在我的char数组的第一个

Moh*_*led 2 c++ arrays string

我正在制作摩尔斯电码转换器,它完成了,我解决了问题,但我不明白. 图片代表了问题

这是一些代码:

string txt,result;
int x;
cout << "Enter the text you want to convert\n";
getline  (cin,txt);
x = txt.size();
char text[x];
strcat(text,txt.c_str());

cout<<"txt = "<<txt<<"\n"<<"text = "<<text<<endl;
Run Code Online (Sandbox Code Playgroud)

我只想知道它是什么char,以及为什么会出现.

Mik*_*CAT 7

  • 您没有初始化text,因此它具有不确定的值.在典型的情况下,奇怪的角色来自你记忆的某个地方.在使用之前初始化它.在这种情况下,我认为使用strcpy()而不是strcat()更好.
  • 标准C++不支持可变长度数组.我建议你应该用new[].
  • 不要忘记为终止空字符分配空间.

试试这个:

string txt, result;
int x;
cout << "Enter the text you want to convert\n";
getline(cin, txt);
x = txt.size() + 1; // +1 for terminating null character
char *text = new char[x];
strcpy(text, txt.c_str());

cout << "txt = " << txt << "\n" << "text = " << text << endl;

// do some other work with text

// after finished using text
delete[] text;
Run Code Online (Sandbox Code Playgroud)