注意:向下滚动以获取更新的代码。
如果不使用外部库,就无法实现这一点。但是,您可以实现的最接近的是:
#include <iostream>
#include <Windows.h>
#include <conio.h>
// Positions the cursor 'home'. Visually clears the screen. Using this to avoid flickering
void cls()
{
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), COORD());
}
void input(std::string& str) // Asks the user for the word
{
int char_count = 0;
while (true)
{
cls();
std::cout << "Set your Wordle first: ";
for (int i = 0; i < char_count; i++)
{
std::cout << "*";
}
if (_kbhit())
{
char c = _getch();
if (c == '\r') // The character '\r' means enter
{
return;
}
char_count++;
str.push_back(c);
}
}
}
int main()
{
char a[5]{};
std::string str;
input(str);
for (int x = 0; x < 5; x++) // Constrain to 5 characters
{
if (x < str.size()) a[x] = str[x];
else break;
}
std::cout << std::endl; // Debug start
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
{
std::cout << a[i];
} // Debug end
}
此代码按您的意愿工作。您可能会看到鼠标在闪烁,但正如我所说,在 C++ 中没有正确的方法可以做到这一点。此外,这不是完整的文字游戏, // Debug start 和 // Debug end 之间的代码仅用于测试目的。
编辑:我玩弄了它并修复了闪烁的问题:
#include <iostream>
#include <Windows.h>
#include <conio.h>
int prev_char_count = 0;
// Positions the cursor 'home'. Visually clears the screen. Using this to avoid flickering
void cls()
{
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), COORD());
}
void input(std::string& str) // Asks the user for the word
{
int char_count = 0;
cls();
std::cout << "Set your Wordle first: ";
for (int i = 0; i < char_count; i++)
{
std::cout << "*";
}
while (true)
{
if (_kbhit())
{
cls();
std::cout << "Set your Wordle first: ";
char c = _getch();
if (c == '\r') // The character '\r' means enter
{
return;
}
char_count++;
str.push_back(c);
for (int i = 0; i < char_count; i++)
{
std::cout << "*";
}
}
}
}
int main()
{
char a[5]{};
std::string str;
input(str);
for (int x = 0; x < 5; x++) // Constrain to 5 characters
{
if (x < str.size()) a[x] = str[x];
else break;
}
std::cout << std::endl; // Debug start
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
{
std::cout << a[i];
} // Debug end
}