This cannot be done portable, since OS consoles are not part of the C ++ standard. In windows, you can use the <windows.h> header - it provides console descriptors, etc., but since you did not specify the OS you are using, it makes no sense to publish only Windows code here (as this may not suit your needs) .
EDIT:
Here is the (not perfect) code that will limit the user's visible input:
#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: az, AZ, 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; }
source share