1

I am facing this position where I need to create a dynamic string of user-inputted size (so I tried used a dynamic cstring).

char * S;
int x;

cin >> x;

S = new char[x];

for (int i = 0; i < x; i++) {
    S[i]=' ';        //trying to make it a string of spaces so I can fill it in later
}

upon doing this and outputting the string (cout << S;) I am getting x spaces and some random characters how do I solve this?

Marcello Romani
  • 2,967
  • 31
  • 40
Ezz
  • 534
  • 2
  • 8
  • 17

1 Answers1

1

Extending my previous comment out. I think you need to add a null character to the end so that std::cout knows when to stop, otherwise it will just keep trying to print the memory contents that S points to.

char * S;
int x;
cin >> x;
S = new char [x + 1]; // +1 for the null character

int i;
for (i=0; i<(x); i++)
  S[i] = ' ';

S[i] = '\0';
austin
  • 5,816
  • 2
  • 32
  • 40