Alan Walker
Alan Walker

Reputation: 31

How to read a char from the console(c++)? (not by inputting/getche() or getch())

To be very honest, I know nothing about pointers, OOP, or any of that scary stuff in c++ (I will learn them very soon). Suppose: (the console)

HELLO WORLD!!
ENTER YOUR AGE: 

So that's what is printed on the console. There's a function gotoxy(int x, int y) which takes your cursor to a certain point in your console (int x is the x-coordinate and int y is the y-coordinate of the point to which it will take the cursor to). gotoxy function's definition:

#include <windows.h>
void gotoxy (int x, int y)
    {
         COORD coordinates;     // coordinates is declared as COORD
         coordinates.X = x;     // defining x-axis
         coordinates.Y = y;     //defining  y-axis
         SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coordinates);       
    }

So that's how you take your cursor to a certain point in the console (by cursor I mean the blinking vertical line, Lol I don't know what's that called). Now, suppose I have this program

#include <iostream> 
#include <windows.h>         //header file
using namespace std; //let the namespace be the standard one
void gotoxy (int x, int y)
    {
         COORD coordinates;     // coordinates is declared as COORD
         coordinates.X = x;     // defining x-axis
         coordinates.Y = y;     //defining  y-axis
         SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coordinates);       
    }
int main() //start of main function
{
   cout << "HELLO WORLD" << endl; //prints HELLO WORLD and brings the cursor to the next line
   cout << "ENTER YOUR AGE: "; //''
   int age; //Declares a memory location for a number which would represent the user's age (if she would be honest xD)
   gotoxy(0, 0);
   higi:
   cin >> age; //Inputs the age
   return 0; //I don't know wth this means lol
}

What this would do is print the exact same lines but if you type something in, it would start from the place where HELLO WORLD is written, and whatever you type will get overwritten. I want to have a function that would go to a certain point in the console (gotoxy, already solved), and then it would read what is the character written at that point. Example if I replace the higi label with

char abc;
abc = function();

Here I have a char ' ' and I wanna store the character which is present where the console's cursor is present into this variable (abc).

Can anyone design a function which would do that? I really need it to make tic tac toe lol

Upvotes: 0

Views: 213

Answers (1)

Matteo Galletta
Matteo Galletta

Reputation: 78

If you need to make tic tac toe, you could directly store everything in a 2D Array (matrix). Using the console as memory is not a good idea.

Upvotes: 1

Related Questions