-4

In C#, after I write Console.WriteLine() and I'm asked to enter several values, can I get them all in one method? For example:

double a, b, c = 0;
Console.WriteLine("please enter the values of:\n a value:\n b value: \n c value:");

thanks for the help (:

Nicolae Olariu
  • 2,487
  • 2
  • 18
  • 30

2 Answers2

3

There's no BCL methods for this specific functionality, but you could use a helper function to collect these without too much repetition.

static void Main(string[] args)
{
    string RequestInput(string variableName)
    {
        Console.WriteLine($"{variableName}:");
        return Console.ReadLine();
    }

    Console.WriteLine("please enter the values of:");
    var a = double.Parse(RequestInput("a"));
    var b = double.Parse(RequestInput("b"));
    var c = double.Parse(RequestInput("c"));

}
Stuart
  • 5,358
  • 19
  • 28
  • This won't compile for me locally. The RequestInput method would need to be outside the Main method or be non-static. – Ross Gurbutt Nov 23 '19 at 20:18
  • This is called a static local function, it was added in C# 8, but I will downgrade to avoid confusion – Stuart Nov 23 '19 at 20:49
0

You could do something like the following, which assumes that the user will enter a string in the console like "2.3 3.4 4.5". You may need to do some checking to make sure the input is correct.

double  a = 0.0, b = 0.0, c = 0.0;
Console.WriteLine("please enter the values of: a b c");

string input = Console.ReadLine();
string[] inputParts = input.Split(' ');

if (inputParts.Length > 0 && inputParts[0] != null) 
{
    Double.TryParse(inputParts[0], out a);
}

if (inputParts.Length > 1 && inputParts[1] != null) 
{
    Double.TryParse(inputParts[1], out b);
}

if (inputParts.Length > 2 && inputParts[2] != null) 
{
    Double.TryParse(inputParts[2], out c);
}

Console.WriteLine($"a: {a.ToString()}");
Console.WriteLine($"b: {b.ToString()}");
Console.WriteLine($"c: {c.ToString()}");
robbpriestley
  • 3,050
  • 2
  • 24
  • 36