C++在Windows控制台中键入时隐藏输入



我对C++很陌生,我正在尝试为两个使用Visual Studio的玩家编写一个类似Wordle的游戏,以便在windows cmd中运行。

我希望在键入用户字符串时,将其替换为"或"*"字符/符号。我只想使用iostream来实现这一点,我在网上遇到了各种解决方案,但没有一个不导入任何额外库(在线解决方案通常使用getch((,它需要一个额外的库(

我的相关(相当简单(代码如下:


#include <iostream>
using namespace std;
char a[5];
string str;
int main()
{
cout << "nSet your Wordle first: ";
cin >> str;
for (int x = 0; x < 5; x++) {
a[x] = str[x];
}
return 0;
}

所以我想,当键入"str"的字符时,会在windows控制台上输出一个"*"。

如有任何帮助或提示,我们将不胜感激,谢谢!

注意:向下滚动查看更新的代码。

如果不使用外部库,就无法实现这一点。然而,你能实现的最接近的是:

#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++中没有合适的方法来做到这一点。此外,这并不是一个完整的文字游戏,//调试开始和//调试结束之间的代码只是用于测试目的。

编辑:我玩了一下,解决了闪烁的问题:

#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
}

最新更新