c++ - 如何从控制台(c++)读取字符?(不是通过输入/getche() 或 getch())
问题描述
老实说,我对指针、OOP 或 c++ 中的任何可怕东西一无所知(我很快就会学习它们)。假设:(控制台)
HELLO WORLD!!
ENTER YOUR AGE:
这就是控制台上打印的内容。有一个函数gotoxy(int x, int y)
可以将光标带到控制台中的某个点(int x 是 x 坐标,int y 是将光标带到的点的 y 坐标)。gotoxy 函数的定义:
#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);
}
所以这就是你如何将光标移到控制台中的某个点(我的光标是指闪烁的垂直线,哈哈,我不知道那叫什么)。现在,假设我有这个程序
#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
}
这样做的目的是打印完全相同的行,但是如果您输入某些内容,它将从写入 HELLO WORLD 的位置开始,并且您输入的任何内容都将被覆盖。我想要一个函数可以到达控制台中的某个点(gotoxy,已经解决),然后它会读取那个点写的字符。例如,如果我将 higi 标签替换为
char abc;
abc = function();
在这里,我有一个 char ' ',我想将控制台光标所在的字符存储到这个变量(abc)中。
任何人都可以设计一个可以做到这一点的功能吗?我真的需要它来做井字游戏哈哈
解决方案
如果您需要制作井字游戏,您可以直接将所有内容存储在 2D 数组(矩阵)中。使用控制台作为内存不是一个好主意。
推荐阅读
- python - 在for循环内部和外部对pd.Series进行索引 - 理解问题
- python-3.x - 删除 URL 字符串并在 python 中使用正则表达式仅保留域
- python-3.x - 如何计算一个数字在 Dice Poker 中出现的次数,然后使用列表确定您拥有的排名手牌?
- c++ - 如何避免在 cpp 中使用嵌套循环?
- r - R:如何将列名分配给变量并在函数中使用它
- angular - navigator.mediaDevices 在 Angular 8 应用程序生产版本中不可用
- android - 如何从 JsonObject 中获取一些字符串?
- python - 在 multiindex DF 中按索引值选择
- mysql - SQL 按字符串末尾的数字排序
- python - 如何获取参数化 BigQuery 查询的控制台视图?