0

Visual C++ in VS 2019

See the below program:

#include <iostream>
#include <conio.h>

using namespace std;

int main() {
 string ask = "Input char: ";
 cout << ask;
 char input = _getch();

 \\ The below part is to erase the previous line from console after getting the input.

 char* spacearray = new char[ask.length()];
 for (int i = 0; i < ask.length(); i++) {
  spacearray[i] = ' ';
 }
 cout << "\r" << spacearray << "\r";
}

The last cout statement does erase the previous line but also puts some weird characters at the end.

For example: ²²²²▌▌▌▌▌▌≤H=â≤@

I can just use a bunch of space inside "" instead of spacearray but that would cause problem if the no of chars in the previous line is more than the no of spaces. And even if I do that, I still want to know where those weird characters come from.

Cody Gray
  • 230,875
  • 49
  • 477
  • 553
HimDek
  • 91
  • 8
  • 1
    Your `spacearray` is not NUL-terminated, which means it is not a valid string. The `cout` statement is reading off the end of the array until it finds a NUL character to terminate the string, which means that it's printing garbage from the free store (whatever comes after your allocated buffer in memory). This is where the unusual characters are coming from. You should prefer simply: `std::cout << '\r' << std::string(ask.length(), ' ') << '\r';` – Cody Gray Nov 24 '21 at 07:47

0 Answers0