pkarthicbz
pkarthicbz

Reputation: 93

How to store multiple values from user to array upto particular size?

I am trying to get a values from user and store it in a array up to particular size. my code looks like

int n = int.parse(Console.ReadLine());
string[] samples = Console.ReadLine().Split(' ');
int[] scores = Array.ConvertAll(samples, Int32.Parse);

the above code works but it doesn't stops after getting n inputs and it allow me to store values after n inputs. how do i make it stop getting inputs after n inputs and i want to get all inputs in single space separated line. for eg:

9
1 2 3 4 5 6 7 8 9

should i use for loop to make that possible?

Upvotes: 2

Views: 3558

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70652

how do i make it stop getting inputs after n inputs

Meaning, what? Exactly? According to the code, you appear to require all inputs on a single line, separated by spaces. You can ignore all inputs beyond n like this:

string[] samples = Console.ReadLine().Split(' ').Take(n).ToArray();

If that's not what you want, please improve the question so that it's more clear exactly what you've tried, what the code you have does now, and what you want it to do instead.

Note that other alternatives include:

  • Requiring the user to enter a separate number on each line. In this case, you can do as suggested in a comment, and put the data entry (i.e. the call to Console.ReadLine()) into a loop. For example:
string[] samples = new string[n];
for (int i = 0; i < n; i++)
{
    samples[i] = Console.ReadLine();
}
  • Handle the user input one key at a time, terminating the input once the user has entered the required number of values, regardless of spaces, line-breaks, etc. This is a lot more complicated approach, so I won't bother writing a code example for that, given that it doesn't appear necessary at the moment.

Upvotes: 3

Related Questions