簡體   English   中英

Console.Readline()之后的C#console Console.WriteLine()?

[英]C# console Console.WriteLine() after Console.Readline()?

我希望控制台輸出基本上具有表單的一般外觀。

以下是我希望輸出顯示的方式:

First Name:  //using Console.ReadLine() right here while there is other text below
Last Name:
Badge Number:

然后

First Name: Joe
Last Name: //using Console.ReadLine() right here while there is other text below
Badge Number:

最后

First name: Joe
Last name: Blow
Badge Number:  //using Console.ReadLine() right here

您需要Console.SetCursorPosition()方法。

Console.WriteLine("First Name: ");
Console.WriteLine("Last Name: ");
Console.WriteLine("Badge Number: ");
Console.SetCursorPosition(12, 0);
string fname = Console.ReadLine();
Console.SetCursorPosition(11, 1);
string lname = Console.ReadLine();
Console.SetCursorPosition(14, 2);
string badge = Console.ReadLine();

看看您可以使用控制台執行的所有操作

為了好玩,讓我們更加可重用:

IList<string> PromptUser(params IEnumerable<string> prompts)
{
    var results = new List<string>();
    int i = 0; //manual int w/ foreach instead of for(int i;...) allows IEnumerable instead of array
    foreach (string prompt in prompts)
    {
        Console.WriteLine(prompt);
        i++;
    }

    //do this after writing prompts, in case the window scrolled
    int y = Console.CursorTop - i; 

    if (y < 0) throw new Exception("Too many prompts to fit on the screen.");

    i = 0;
    foreach (string prompt in prompts)
    {
        Console.SetCursorPosition(prompt.Length + 1, y + i);
        results.Add(Console.ReadLine());
        i++;
    }
    return results;
}

然后你會這樣稱呼它:

var inputs = PromptUser("First Name:", "Last Name:", "Badge Number:");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM