Anish varma Adduri
Anish varma Adduri

Reputation: 599

Getting error while using split method for reading multiple integers in a single line

I am getting an error while using Split while reading an integer from the user

 int[] a = new int[s];
        for (i = 0; i < s; i++)
        {
            a[i] = Int32.Parse(Console.ReadLine().Split(' '));
        }

Can you please help me how to use Split.

Upvotes: 0

Views: 562

Answers (3)

Anish varma Adduri
Anish varma Adduri

Reputation: 599

We can take the input as string first

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

and then convert the array into Int

   int[] array = Array.ConvertAll(array_temp,Int32.Parse);

Upvotes: 0

JC97
JC97

Reputation: 1620

Since split returns an array, and each time you need the i'ed one, you should change it like this:

 int[] a = new int[s];
 string[] input = Console.ReadLine().Split(' ');

 for (i = 0; i < s; i++)
 {
    a[i] = Int32.Parse(input[i]);
 }

You need to read the input only once btw. Like @loneshark99 said it would be even better to use TryParse(). Since that returns a boolean, you can check if the input are indeed integers. If you just use Parse and they are not integers, it would throw an exception.

Code with TryParse():

 int[] a = new int[s];
 string[] input = Console.ReadLine().Split(' ');

 for (i = 0; i < s; i++)
 {
    if (Int32.TryParse(input[i], out a[i])) 
    {
        //successfully parsed
    }
 }

The if-statement is not necessary but it's just to point out how you could use the TryParse.

Upvotes: 3

itsme86
itsme86

Reputation: 19526

LINQ can really help you here:

int[] a = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

Upvotes: 3

Related Questions