限制控制台中的输入 [英] Limiting the input in the Console

查看:100
本文介绍了限制控制台中的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个迷宫游戏。我如何限制Console.Read()之后用户输入的字符数?
我需要限制它,以便如果用户输入一个很长的字符串,它将覆盖我的迷宫。
如果您打算告诉我事后再改写迷宫,我会拒绝。我不能相信我,这将需要我进行另一个漫长的过程。我只想要一个用于限制输入的简单代码。

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.

下面是显示问题的屏幕截图。您在屏幕上看到 asdasjhasd .... 吗?看到它如何弄乱迷宫?我想限制用户可以输入的字符数,以使它不会到达迷宫。你们能告诉我使用什么代码吗?

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?

已解决

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;
    }
}


推荐答案

A解决方法是使用 Console.ReadKey 代替:

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);

这篇关于限制控制台中的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆