在C#中读取后消除换行

时间:2018-08-30 17:47:54

标签: c# parsing console-application user-input console-input

using A = System.Console;
public void point()
{
    int hour, minute;
    A.Write("Enter Time (HH:MM) = ");
    hour = A.Read();
    A.Write(":");
    minute = A.Read();
}

我希望它像

  

“输入时间(HH:MM)= 12(小时输入):49(分钟输入)”

但是它像

  

“输入时间(HH:MM)= 12(小时输入)
  :49(分钟输入)

3 个答案:

答案 0 :(得分:3)

最简单的方法(假设您正在从控制台中读取,并且用户将输入小时,然后按Enter,然后输入分钟并按Enter):

static void Main(string[] args)
        {
            int hour = 0, minute = 0;
            const int MAX_NUMBER_OF_DIGITS = 2 ;

            Console.Write("Enter Time (HH:MM) = ");

            // store cursor position
            int cursorLeft = Console.CursorLeft;
            int cursorTop = Console.CursorTop;

            // use ReadLine, else you will only get 1 character 
            // i.e. number more than 1 digits will not work
            hour = int.Parse(Console.ReadLine());

            Console.SetCursorPosition(cursorLeft + MAX_NUMBER_OF_DIGITS , cursorTop);

            Console.Write(":");

            minute = int.Parse(Console.ReadLine());

            // Nitpickers! purposefully not using String.Format, 
            // or $, since want to keep it simple!
            Console.Write("You entered: " + hour + ":" + minute);
        }

输出:

  

输入时间(HH:MM)= 17:55

     

您输入的是:17:55

尽管我希望向您推荐这样一种更好和更少出错的方式(用户输入HH:MM并按一次Enter,即输入一个包含{{1 }},即冒号):

:

答案 1 :(得分:1)

假设A是控制台,您可以这样做:

    static void Main()
    {
        int hour, minute;
        char[] hourChars = new char[2];
        Console.Write("Enter Time (HH:MM) = ");
        hourChars[0] = Console.ReadKey().KeyChar;
        hourChars[1] = Console.ReadKey().KeyChar;
        var hourString = new String(hourChars);
        hour = int.Parse(hourString);
        Console.Write(":");
        minute = Console.Read();
    }

答案 2 :(得分:0)

假设A是标准的c#Console,则可以使用ReadKey代替Read

ReadKey一次只能读取一个字符,但不会强迫您按Enter键,这是换行的原因。

    static void Main()
    {
        char h1, h2, m1, m2;
        Console.Write("Enter Time (HH:MM) = ");
        h1 = Console.ReadKey().KeyChar;
        h2 = Console.ReadKey().KeyChar;
        Console.Write(":");
        m1 = Console.ReadKey().KeyChar;
        m2 = Console.ReadKey().KeyChar;
    }

我将保留实际值解析作为练习。