One option would be to accept a single line of input as a string and then process it.
For example:
//Read line, and split it by whitespace into an array of strings
string[] tokens = Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(tokens[0]);
//Parse element 1
int b = int.Parse(tokens[1]);
One issue with this approach is that it will fail (by throwing an IndexOutOfRangeException
/ FormatException
) if the user does not enter the text in the expected format. If this is possible, you will have to validate the input.
For example, with regular expressions:
string line = Console.ReadLine();
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if(new Regex(@"^\d+\s+\d+$").IsMatch(line))
{
... // Valid: process input
}
else
{
... // Invalid input
}
Alternatively:
- Verify that the input splits into exactly 2 strings.
- Use
int.TryParse
to attempt to parse the strings into numbers.