user4840466
user4840466

Reputation:

how to take user input and assign to array

Say the user inputs a line "1 2 3 4", how do i assign it to an array such that at value of array[0] is 1, array[1] is 2 and so on? So far I only managed to assign values when the user presses enter after each value but not when the values are in a line, which is what I want to achieve.

double[,] array = new double[4,4];

Console.Write("Enter 16 digits: ");
for (int i = 0; i < 4; i++)
{
    for (int j = 0; j < 4; j++)
    {
        array[i, j] = Convert.ToDouble(Console.ReadLine());
    }
}

Upvotes: 0

Views: 1772

Answers (2)

DWright
DWright

Reputation: 9500

You should add something like

 var line = Console.ReadLine();
 var lineArray = line.Split(new Char[]{' '});

That will give you an array of individual string elements elements in lineArray, with "1" at [0], etc. If you then want to convert that to an array of doubles, you can do

var arrayOfDouble = lineArray.ToList().ConvertAll(x => Double.Parse(x)).ToArray();

Here's an explanation:

  1. The split Method. This is a method available for String objects. It takes a string of characters (I just had an array of one element ' ', the space character) and splits the provided string on occurrences of those characters. It returns an array of the split out items.

  2. The call to ConvertAll.

    • This takes a function, in this case specified on the fly in lambda notation (i.e., the x => Double.Parse(x) bit), which allows specifying a function right then and there as needed. The function taxes a value, x, and tries to parse that value as a Double. Since x comes from an array of strings, the type of x is String. The call to Parse tries to get a Double out of the passed string, x.
    • Because ConvertAll() is available on the List object, I first convert the array to a List via ToList(). The lambda gets called on each element of list, so every string in the original lineArray, will be passed to Double.Parse for conversion to a double. A new list of Double will result.
    • At the end I make the resulting list of doubles back into an array via ToArray().

Upvotes: 1

Christo S. Christov
Christo S. Christov

Reputation: 2309

You have to split the line first:

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

then its trivial

for (int i = 0; i < 4; i++)
{
    for (int j = 0; j < 4; j++)
    {
        array[i, j] = double.Parse(line[i * 4 + j];
    }
}

Upvotes: 2

Related Questions