Limiting the input in the Console

风流意气都作罢 提交于 2019-12-23 00:46:28

问题


I'm making a maze game. how can i limit the number of characters the user will input after Console.Read()? i need to limit it so that if the user inputs a very long string, it will overwrite my Maze. If you're planning to tell me to just rewrite the maze afterwards, i'll say no. I can't. It will require me another long process, believe me. I just want a simple code for limiting the input.

Here's a screenshot demonstrating the problem. You see that asdasjhasd.... in the screen? See how it messes up the maze? I want to limit the numbers of characters the User can input so that it will not reach the maze. Can you guys tell me what code to use?

SOLVED

string str = string.Empty;
while (true)
{
    char c = Console.ReadKey(true).KeyChar;
    if (c == '\r')
        break;
    if (c == '\b' )
    {
        if (str != "")
        {
            str = str.Substring(0, str.Length - 1);
            Console.Write("\b \b");
        }
    }
    else if (str.Length < limit)
    {
        Console.Write(c);
        str += c;
    }
}

回答1:


A workaround is to use Console.ReadKey instead:

string str = string.Empty;
do
{
    char c = Console.ReadKey().KeyChar;
    if(c == '\n')
        break;

    str += c;
}while(str.Length < 7);



回答2:


Just tested a slightly modified version of Anders's answer, and it works:

public static string ReadLimited(int limit)
{
    string str = string.Empty;
    while (str.Length < limit)
    {
        char c = Console.ReadKey().KeyChar;
        if (c == '\r')
            break;
        str += c;
    } 
    return str;
}

It doesn't handle backspace and autoaccepts any string that reaches the limit, but apart from these issues it works.

And a better version that fixed these problems:

public static string ReadLimited(int limit)
{
    string str = string.Empty;
    while (true)
    {
        char c = Console.ReadKey(true).KeyChar;
        if (c == '\r')
            break;
        if (c == '\b' )
        {
            if (str != "")
            {
                str = str.Substring(0, str.Length - 1);
                Console.Write("\b \b");
            }
        }
        else if (str.Length < limit)
        {
            Console.Write(c);
            str += c;
        }
    }
    return str;
}



回答3:


Use Console.ReadKey(true); - it will return a ConsoleKey that you can add to your input Stream.
If you want to convert it to a char, simply use the property .KeyChar.
Because intercept is set to true - it will not display the character in the console window at all.



来源:https://stackoverflow.com/questions/6723755/limiting-the-input-in-the-console

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