0

I want to enter in a bunch of integers like so:
1 11 2 12 3 13 4 14 5 56 6 80...

How would I get them into an array of int?

Console.WriteLine("Enter in numbers");

 string answer = Console.ReadLine();

  int[] myArray = new int[answer.Length]; 
 for (int i = 0; i < answer.Length; i++)
        {
            myArray[i] = answer[i].ToString();
        }

The problem with that code is that it doesnt see the space inbetween numbers. Any ideas?

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by JerryShaw
2
char[] space = new char[1] { ' ' };
Console.WriteLine("Enter in numbers");
int nAnswer;
string[] answer = Console.ReadLine().Split(space
           ,StringSplitOptions.RemoveEmptyEntries);
                
List<int> myArray = new List<int>();
foreach(string str in answer)
     if( Int32.TryParse(str,out nAnswer) )
                    myArray.Add(nAnswer);

// Your answer can be pulled from the list using:
int[] result = myArray.ToArray();
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.