5

I'm looking for a method to limit the visible user input using std::cin.

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

What the user sees if they enter earth or any other word exceeding 4 characters before pressing enter:

Enter your planet:
eart

This is assuming the character limit is 4, note that the 'h' is missing. The console does not display any other character once it has exceeded the character limit. and this is before you press the enter key.

Kinda like typing in an input box like password fields, but it only allows 5 characters, so typing any other character goes unnoticed

A better analogy would be the maxlength attribute for text input in HTML.

Rakete1111
  • 47,013
  • 16
  • 123
  • 162

2 Answers2

3

That can't be achieved portably, because OS consoles aren't part of C++ standard. In windows, you could use <windows.h> header - it provides console handles etc., but since you didn't specify OS you are using, the is no point in posting windows-only code here (since it might not meet your needs).


EDIT:

Here is (not perfect) code that will limit visible input of the user:

#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; 
}
xinaiz
  • 7,744
  • 6
  • 34
  • 78
  • @Rakete1111 I will update the answer if OP specifies if he needs portable code or platform dependant one. As it is now, the answer can't be answered with solution. – xinaiz Sep 24 '16 at 17:46
  • 1
    Yes, I'm also running a windows OS, precisely windows 10. I'm not sure other system information are required, bit if so, let me know, and I'll list them out – Nicholas Theophilus Sep 24 '16 at 17:53
  • 2
    @NicholasTheophilus Edited answer with actual code. – xinaiz Sep 24 '16 at 18:50
  • @BlackMoses Thanks a whole lot, extremely helpful. Any link you post to help me further understand this would be very much appreciated. Thanks again – Nicholas Theophilus Sep 24 '16 at 19:19
  • 2
    @NicholasTheophilus Windows programming is complex subject, I suggest you to find some tutorials online. Also, many questions are already answered online. Just search what you would ask online, and most of the time there are good answers. For example `How to change windows console color`. :) – xinaiz Sep 24 '16 at 19:24
0

After a few days of experimenting, I found another solution that seems to be quite easy to grasp as it is somewhat beginner level and without requiring any knowledge of windows programming.

NOTE: The conio.h library function _getch() could easily be replaced with the getchar() function;

I'm not saying the previous answer was not okay, but this solution is sort of aimed towards beginners with only basic knowledge of c++

char ch;
string temp;
ch = _getch();
while(ch != 13)// Character representing enter
{
    if(ch == '\b'){ //check for backspace character
       if(temp.size() > 0) // check if string can still be reduced with pop_back() to avoid errors
       {
          cout << "\b \b"; //
          temp.pop_back(); // remove last character
        }
     }
    else if((temp.size() > 0)  || !isalpha(ch))// checks for limit, in this case limit is one
    {                                         //character and also optional checks if it is an alphabet
        cout << '\a'; // for a really annoying sound that tells you know this is wrong
    }else {
        temp.push_back(ch); // pushing ch into temp
        cout << ch; // display entered character on screen
    }
    ch = _getch();
}

This could probably use some tweaks, because it's definitely not perfect, but I think it is easy enough to understand, at least I hope so