Click here to Skip to main content
14,691,808 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a multidimensional array that takes lines based on user input like(n lines/4col ) and I have a string of 4 numbers in a line separated by 1 space: 10.00 20.00 30.00 40.00. I need to assign each number to a column in 1 line. The code that I have until now:

What I have tried:

int storeNumbers = int.Parse(Console.ReadLine());

      string[,] storesemesterProfit = new string[storeNumbers, 4];

      for(int m=0; m<storeNumbers; m++)
      {
          for(int n=0; n < 4; n++)
          {

             string inputData = Console.ReadLine()
             string [] numb = inputData.Split(' ');
             storesemesterProfit[m, n] = numb ; // i need help here
Posted
Updated 1-Sep-20 5:58am

The first thing to do is to think about what you are trying to do: rather than creating a 3D array with fixed sizes and getting the user to input the count, consider a List instead, so it can expand as needed:
List<string[]> storeSemesterProfit = new List<string[]>();

Then let the user enter data util he runs out and it's easy to store:
string storeData = Console.ReadLine();
while (!string.IsNullOrWhiteSpace(storeData))
    {
    storeSemesterProfit.Add(storeData.Split(' '));
    storeData = Console.ReadLine();
    }
Even better would be to convert the strings to actual numbers at this point as it's easy to get the user to fix his typos:
List<decimal[]> storeSemesterProfit = new List<decimal[]>();
string storeData = Console.ReadLine();
while (!string.IsNullOrWhiteSpace(storeData))
    {
    string[] parts = storeData.Split(' ');
    decimal[] profits = new decimal[parts.Length];
    bool ok = true;
    for (int i = 0; i < parts.Length; i++)
        {
        decimal value;
        if (!decimal.TryParse(parts[i], out value))
            {
            Console.WriteLine($"{parts[i]} is not a number: line ignored, please reenter");
            ok = false;
            break;
            }
        profits[i] = value;
        }
    if (ok)
        {
        storeSemesterProfit.Add(profits);
        }
    storeData = Console.ReadLine();
    }
   
You are splitting the string for each number which is not necessary. Split the string and then add each item to your array. You also need to identify which item of the split you are referring to:
for(int m=0; m<storeNumbers; m++)
{
    string inputData = Console.ReadLine();
    string [] numb = inputData.Split(' '); // split the string
    for(int n=0; n < 4; n++) // for each field of the string
    {
        storesemesterProfit[m, n] = numb[n] ; // add the next field to the array
    }
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900