Home > Blockchain >  assigning numbers entered in a row to an array 3 6 23 12 4 a[0]=3 a[1]=6 a[2]=23 a[3]=12 a[4]=10
assigning numbers entered in a row to an array 3 6 23 12 4 a[0]=3 a[1]=6 a[2]=23 a[3]=12 a[4]=10

Time:11-10

        string[] n = Console.ReadLine().Split();
                
        for (int i = 1; i <6; i  )
        {
            int[] a = long.Parse(n[i]);
        }

CodePudding user response:

If each number in a row separated with whitespace - you can use your Split more efficiently:

int[] array = Console.ReadLine().Split().Select(int.Parse).ToArray(); // Improved according to @Caius Jard comment

If need array of longs - replace int.Parse with long.Parse and declare variable as long[] array.

You need to add using System.Linq to get access to ToArray extension method.

EDIT.

Insprired by @Caius Jard, non-LINQ version:

// Read input line and split it by whitespace (default)
string[] values = Console.ReadLine().Split();
 
// Declare arrays for Int or Long values.
// Arrays sizes equals to size of array of input values      
int[] arrayOfInts = new int[values.Length];
long[] arrayOfLongs = new long[values.Length];
       
// Iterate with for loop over amount of input values.     
for (int i = 0; i < values.Length; i  )
{
    // Convert trimmed input value to Int32
    arrayOfInts[i] = int.Parse(values[i].Trim());
    // Or to Int64
    arrayOfLongs[i] = long.Parse(values[i].Trim());
}

int.Parse and long.Parse may be replaced with Convert.ToInt32 and Convert.ToInt64 if needed.

CodePudding user response:

Please, don't use magic constants: i < 6. Here 6 doesn't necessary equal to n.Length. You can put it as

    string[] n = Console.ReadLine().Split();

    List<int> list = new List<int>();

    for (int i = 0; i < n.Length;   i) {
      if (int.TryParse(n[i], out int value))
        list.Add(value); 
      else {
        // Invalid item within user input, say "bla-bla-bla"
        //TODO: either reject the input or ignore the item (here we ignore) 
      } 
    }

    if (list.Count == a.Length) { 
      // We have exactly a.Length - 6 valid integer items
      for (int i = 0; i < a.Length;   i)
        a[i] = list[i];
    } 
    else { 
      //TODO: erroneous input: we have too few or too many items
    }
  • Related