rookr
rookr

Reputation: 193

C# console Console.WriteLine() after Console.Readline()?

I want the console output to have the general look of a form basically.

Here is a representation of how I want the output to look:

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

then

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

lastly

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

Upvotes: 3

Views: 3324

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 416121

You need the Console.SetCursorPosition() method.

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

Take a look at all the things you can do with the Console.

For fun, let's make this more re-usable:

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

And then you would call it like this:

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

Upvotes: 9

Related Questions