Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

Is there a way to read an exact amount of split integers in C#?

Basically I've got this code:

var inputData = Console.ReadLine().Split(' ');

int N = int.Parse(inputData[0]);
int K = int.Parse(inputData[1]);
int[] A = new int[N];

From the console I need to read N and K like this:

4 2

In order to input elements in the array 'A', I need to read elements like this:

45 50 47 46

I figured out how to read N and K , but to fill the array , if N is let's say 35 , I must read exactly 35 numbers from a single line , how do I do that?


I've tried Fabio's solution and the code turned out like this:

var inputData = Console.ReadLine().Split(' ');
            int N = int.Parse(inputData[0]);
            int K = int.Parse(inputData[1]);
            int[] A = new int[N];
            var elements = Console.ReadLine().Split(' ').Take(N).ToArray();
            for (int i = 0; i < N; i++)
            {
                A[i] = Convert.ToInt32(elements[i]);
            }

That worked perfectly!

P.S I am still trying to grasp StackOverflow's rules for asking question and formatting my questions so I'm sorry for leaving this huge chunk here and I want to thank everybody for reaching out.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Sounds like you'll read the first line, to get the size of the array, then read another line. You didn't say what you do with K.. maybe it's the number of lines of N elements..

var inputData = Console.ReadLine().Split();

int N = int.Parse(inputData[0]);
int K = int.Parse(inputData[1]);

var inputs = new List<int[]>();

for(k = 0; k < K; k++){
    Console.Write($"Enter {N} numbers separated by spaces: ");
    inputData = Console.ReadLine();
    var bits = inputData.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
    if(bits.Length == N)
      inputs.Add(bits); //they did put N entries, woot
    else
      k--;              //make them do it again
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...