如何从用户到数组存储多个值到特定大小? [英] How to store multiple values from user to array upto particular size?

查看:48
本文介绍了如何从用户到数组存储多个值到特定大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从用户那里获取一个值,并将其存储在特定大小的数组中.我的代码看起来像

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);

上面的代码可以工作,但是在获得 n 个输入后并不会停止,它允许我在 n 个输入后存储值.我如何使它停止在 n 输入之后获取输入,并且我想在单个空格分隔的行中获取所有输入.例如:

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

我应该使用for循环使之成为可能吗?

should i use for loop to make that possible?

推荐答案

我如何让它在n次输入后停止获取输入

how do i make it stop getting inputs after n inputs

意思是什么?确切地?根据代码,您似乎要求所有输入都在一行上,并用空格分隔.您可以这样忽略 n 之外的所有输入:

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();
}

  • 一次处理用户输入的一个键,一旦用户输入了所需数量的值(无论空格,换行符等),都将终止输入.这是一种更为复杂的方法,因此我不会鉴于目前不需要它,因此不妨为此编写一个代码示例.
  • 这篇关于如何从用户到数组存储多个值到特定大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆