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

点点圈 提交于 2021-01-27 17:55:55

问题


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?


回答1:


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.


来源:https://stackoverflow.com/questions/43622971/how-to-store-multiple-values-from-user-to-array-upto-particular-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!