What I am trying to do is to move a character using arrow keys within a 1D or 2D array. I have initialized the array with "a" which means it starts at index #0 but when I swap it doesn't give the intended output instead it gives me something like that:
a a a a a a a a a
it should be like this
a
Here is my code
#include<iostream>
#include<Windows.h>
#include<conio.h>
#include<fstream>
#define RIGHT 77
#define LEFT 75
#define UP 72
#define DOWN 80
#define ESC 27
using namespace std;
void gotoxy(int, int);
void swap(char*,char*);
char arr[1024] = { "a"};
char *line_ptr = (char*)arr[0];
char *line_ptr2d =(char*)arr[0];
void main()
{
for (int i = 1; i < 1024; i++)
{
arr[i] = ' ';
}
int x = 1;
int y = 1;
int ch;
do
{
//system("cls");
int i = 0;
gotoxy(x, y);
ch = _getch();
if (ch == 224)
{
ch = _getch();
switch (ch)
{
case LEFT:
x -= 1;
line_ptr--;
swap(&arr[i], &arr[i + 1]);
//arr[i] = ' ';
cout << arr[i];
break;
case RIGHT:
x += 1;
swap(&arr[i], &arr[i + 1]);
if (arr[i-1] != NULL)
{
arr[i - 1] = ' ';
}
cout << arr[i+1];
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
}
}
i++;
} while (1);
}
void gotoxy(int x, int y)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
_COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(hConsole, pos);
}
void swap(char *x, char *y)
{
char temp = *x;
*x = *y;
*y = temp;
}