Limiting the number of characters of user input

只谈情不闲聊 提交于 2019-12-02 17:00:35

问题


I'm trying to limit # of characters a user can input.
It's not like when user inputs abcde, and I limit the input length to be 3,
and only abc is taken into account.

Is there a way to physically limit user from inputting more than certain amount of characters?
For example, if user trys to type 12345, and if I limit it to 3 characters, only 123 gets typed.

I've tried the following code:

cin.width(5);
cin >> n;

But I've realized it doesn't physically limit the user input, but only limits the buffersize of input.

Is there a way to do something like this?

+) I'm working on Console Application


回答1:


You can't do it in a standard console window but if you use c++ to make your own window with your own input box then you have some more flexibility.




回答2:


You could do some weird thing like reading individual characters one at a time, and if they don't hit return by the 4th character, say invalid input and then make them start over, but it's cleaner and easier to just call long input invalid after they try to submit it.




回答3:


You may be searching for this:--

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string MyInput;
    std::cout << "INPUT HERE: ";
    std::getline(cin,MyInput);
    if (MyInput.length() == 3)
    {
        std::cout << "OKAY IT IS THREE CHARS" << std::endl;
    }
    else if (!(MyInput.length() == 3))
    {
        MyInput.erase(MyInput.begin()+3,MyInput.end());
        std::cout << "Look: " << MyInput << std::endl;
    }
}


来源:https://stackoverflow.com/questions/17181594/limiting-the-number-of-characters-of-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!