我正在制作摩尔斯电码转换器,它完成了,我解决了问题,但我不明白. 图片代表了问题
这是一些代码:
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,以及为什么会出现.
text,因此它具有不确定的值.在典型的情况下,奇怪的角色来自你记忆的某个地方.在使用之前初始化它.在这种情况下,我认为使用strcpy()而不是strcat()更好.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)