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.

7
  • If I understand correctly, if I input 2 it should print He? Commented Sep 24, 2016 at 17:07
  • @Rakete1111 No, if you try to input "1234" and x is set to 2, then it will only allow you to enter "12". I think. Commented Sep 24, 2016 at 17:12
  • 1
    The question is very unclear. Can you show us what the user will see? Commented Sep 24, 2016 at 17:12
  • more like if you try to input her, it only shows he before you press enter basically it does not display any other character once the limit is reached Commented Sep 24, 2016 at 17:14
  • 2
    That's not possible portably... Commented Sep 24, 2016 at 17:31

2 Answers 2

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; 
}
Sign up to request clarification or add additional context in comments.

5 Comments

@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.
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
@NicholasTheophilus Edited answer with actual code.
@BlackMoses Thanks a whole lot, extremely helpful. Any link you post to help me further understand this would be very much appreciated. Thanks again
@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. :)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.