如何在使用std :: cin时限制可见的用户输入?

Nic*_*lus 5 c++ user-input input

我正在寻找一种限制可见用户输入的方法std::cin.

#include <iostream>
int main()
{
   std::cout << "Enter your planet:\n";
   string planet;
   std::cin >> planet; // During the prompt, only "accept" x characters
 }
Run Code Online (Sandbox Code Playgroud)

在输入earth之前,用户输入的内容或超过4个字符的任何其他单词:

Enter your planet:
eart
Run Code Online (Sandbox Code Playgroud)

这假设字符限制为4,请注意'h'缺少.一旦超出字符限制,控制台不会显示任何其他字符.这是在你按下回车键之前.

有点像在输入框中键入密码字段,但它只允许5个字符,因此输入任何其他字符都不会引起注意

更好的类比是maxlengthHTML中文本输入的属性.

xin*_*aiz 3

这无法移植地实现,因为操作系统控制台不是 C++ 标准的一部分。在 Windows 中,您可以使用<windows.h>标头 - 它提供控制台句柄等,但由于您没有指定您正在使用的操作系统,因此在此处发布仅限 Windows 的代码是没有意义的(因为它可能无法满足您的需求)。


编辑:

这是(不完美)代码,它将限制用户的可见输入:

#include <iostream>
#include <windows.h>
#include <conio.h>
int main()
{
    COORD last_pos;
    CONSOLE_SCREEN_BUFFER_INFO info;
    std::string input;
    int keystroke;
    int max_input = 10;
    int input_len = 0;
    HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);

    std::cout << "Input (max 10) characters, press ENTER to prompt:" << std::endl;

    GetConsoleScreenBufferInfo(handle, &info);
    last_pos = info.dwCursorPosition;

    while(true)
    {
        if(kbhit())
        {
            keystroke = _getch();
            //declare what characters you allow in input (here: a-z, A-Z, 0-9, space)
            if(std::isalnum(keystroke) || keystroke == ' ') 
            {
                if(input_len + 1 > max_input)
                    continue;

                ++input_len;

                std::cout << char(keystroke);
                input += char(keystroke);

                GetConsoleScreenBufferInfo(handle, &info);
                last_pos = info.dwCursorPosition;
            }
            else if(keystroke == 8) //backspace
            {
                if(input_len - 1 >= 0)
                {
                    --input_len;
                    input.pop_back();

                    COORD back_pos {short(last_pos.X-1), last_pos.Y};

                    SetConsoleCursorPosition(handle, back_pos);
                    std::cout << ' ';
                    SetConsoleCursorPosition(handle, back_pos);

                    GetConsoleScreenBufferInfo(handle, &info);
                    last_pos = info.dwCursorPosition;
                }
            }
            else if(keystroke == 13) //enter
            {
                std::cout << std::endl;
                break;
            }
        }
    }

    std::cout << "You entered: " << std::endl
              << input << std::endl; 
}
Run Code Online (Sandbox Code Playgroud)

  • @NicholasTheophilus 用实际代码编辑了答案。 (2认同)
  • @NicholasTheophilus Windows编程是一个复杂的学科,我建议你在网上找到一些教程。此外,许多问题已经在网上得到解答。只要在网上搜索你想问的问题,大多数时候都有很好的答案。例如“如何更改 Windows 控制台颜色”。:) (2认同)