I am new to C# and I have a problem with the get the input from the user and this is the requirements:
Get a list of integer numbers from the user on A SINGLE LINE
The numbers will be in the range [0,100]
The numbers will be separated by spaces
You may assume that the user enters a correctly formatted input string that meets these requirements
You may use Console.ReadLine or a similar method to get input from the user
And here is my code
//Prompt the input from user
Console.WriteLine("Please enter your numbers in the range [0,100]: ");
int n;
n = Int32.Parse(Console.ReadLine());
int[] arr = new int[n];
string[] s = Console.ReadLine().Split(' ');
for (int i = 0; i < n; i )
{
arr[i] = Int32.Parse(s[i]);
}
Console.WriteLine(n);
foreach (var item in arr)
{
Console.Write(item " ");
}
These are the errors I got and I try to fix but it still does not work.
Exception thrown: 'System.FormatException' in System.Private.CoreLib.dll
An unhandled exception of type 'System.FormatException' occurred in System.Private.CoreLib.dll
Input string was not in a correct format.
CodePudding user response:
You are reading the input into the int variable. Instead read that to a variable and then use string split to get an array, from there you only need to iterate the array. For instance:
//Prompt the input from user
Console.WriteLine("Please enter your numbers in the range [0,100]: ");
var input = Console.ReadLine();
var inputArray = input.Split(' ');
foreach (var item in inputArray)
{
Console.Write(item " ");
}
CodePudding user response:
Console.WriteLine("Please enter your numbers in the range [0,100]: ");
List<int> IntList = new List<int>();
var input = Console.ReadLine();
var array = input.Split(' ');
foreach (var item in array)
{
IntList.Add(Int32.Parse(item);)
}
IntList.ForEach(Console.WriteLine);
