user4366391
user4366391

Reputation:

A strange char appears at the first of my char array

I am making a Morse code converter, it's done, I solved the problem , but I do not understand it. picture represents the problem

This is some of the code:

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;

I just want to know what is that char, and why it appears.

Upvotes: 2

Views: 70

Answers (2)

Sean
Sean

Reputation: 62472

strcat appends to a char array by searching for the end of the destination string (by looking for the null terminator) and then writing the additional characters there.

However, you've got an array of uninitialized memory, so the actual place where the string will be concatenated is indeterminate. You can either say:

text[0] = 0;
strcat(text, txt.c_str());

or just:

strcpy(text, txt.c_str());

Also, you can't initialize an array using a non-const variable, so you should either allocate the memory using new:

text = new char[x];

or just use a std::string and modify it as you go:

std::string text = txt;

Upvotes: 3

MikeCAT
MikeCAT

Reputation: 75062

  • You didn't initialize text, so it has an indeterminate value. The strange characters came from somewhere of your memory in typical case. Initialize it before using. I think using strcpy() instead of strcat() is better in this case.
  • Variable-length array is not supported in standard C++. I suggest you should use new[] instead.
  • Do not forget to allocate space for terminating null-character.

Try this:

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;

Upvotes: 6

Related Questions