Reputation: 599
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
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
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
Reputation: 19526
LINQ can really help you here:
int[] a = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
Upvotes: 3