Reputation:
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
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:
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.
The call to ConvertAll.
Upvotes: 1
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