views:

158

answers:

5

i know how to make a console read two integers but each integer by it self like this

int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());

if i entered two numbers, i.e (1 2), the value (1 2), cant be parse to integers what i want is if i entered 1 2 then it will take it as two integers

+3  A: 

Then you should first store it in a string and then split it using the space as token.

PoweRoy
ooohhh nice !! i dont know how i missed that :D
Nadeem
ooohhh nice !! i dont know how i missed that :D
Nadeem
+8  A: 

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:

  1. Verify that the input splits into exactly 2 strings.
  2. Use int.TryParse to attempt to parse the strings into numbers.
Ani
this really helps
Nadeem
this really helps
Nadeem
+2  A: 

Read the line into a string, split the string, and then parse the elements. A simple version (which needs to have error checking added to it) would be:

string s = Console.ReadLine();
string[] values = s.Split(' ');
int a = int.Parse(values[0]);
int b = int.Parse(values[1]);
Dan Puzey
+2  A: 

You need something like (no error-checking code)

var ints = Console
            .ReadLine()
            .Split()
            .Select(int.Parse);

This reads a line, splits on whitespace and parses the split strings as integers. Of course in reality you would want to check if the entered strings are in fact valid integers (int.TryParse).

Novox
A: 

in 1 line, thanks to LinQ and regular expression (no type-checking neeeded)

var numbers = from Match number in new Regex(@"\d+").Matches(Console.ReadLine())
                    select int.Parse(number.Value);
iChaib
You forgot to parse your strings: `... select int.Parse(number.Value);`
Novox
thx @novox, code edited
iChaib