0

I am trying to edit my own files with Vi on linux using the following C++ code. I am trying to name the files using character array, but when I am trying to copy from string to a dynamic character array, I get weird characters at the end of the array.What is the reason? How could I fix it? Sorry It didnt let me post the picture so i copied what i had on screen and pasted it Thank you

  newPath[0] = 'v';
  newPath[1] = 'i';
  newPath[2] = ' ';

 for(int i = 0 ; i < fileName.length(); i++)
 {
    stringLenght =3 + i;
newPath[stringLenght] = (char)fileName[i];
 }
     cout<<newPath<<" length:"<<fileName.length()<<endl;

Files are on current directory are listing below;

main.cpp   
a.cpp 
a.cpp.#h???

Which file do you want to edit?: a.cpp

location: . Locationlength:0

vi a.cpp.#�{� length:5
kim1989
  • 33
  • 1
  • 8

1 Answers1

1

std::cout.operator<<(char*) (your char[] array decays to char*) uses \0 as its terminator. It seems that you're not appending that null though.

Pretty much the same problem as here.

A simple solution is to manually add \0 to the end of your char array.

Community
  • 1
  • 1
ScarletAmaranth
  • 5,065
  • 2
  • 23
  • 34