How can I limit the number of characters for a console input? C#

后端 未结 2 1390
我在风中等你
我在风中等你 2020-12-22 06:06

Basically I want 200 characters maximum to come up in Console.ReadLine() for user input before characters start being suppressed. I want it like TextBox.MaxLength except for

2条回答
  •  甜味超标
    2020-12-22 06:44

    If you can use Console.Read(), you can loop through until you reach the 200 characters or until an enter key is entered.

    StringBuilder sb = new StringBuilder();
    int i, count = 0;
    
    while ((i = Console.Read()) != 13)   // 13 = enter key (or other breaking condition)
    {
        if (++count > 200)  break;
        sb.Append ((char)i);
    }
    

    EDIT

    Turns out that Console.ReadKey() is preferred to Console.Read().

    http://msdn.microsoft.com/en-us/library/471w8d85.aspx

提交回复
热议问题