Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading two integers in one line using C#

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

like image 660
Nadeem Avatar asked Oct 07 '10 12:10

Nadeem


People also ask

How to take two integer input in same line in C?

If you're taking multiple inputs you can either use a space bar to separate inputs or you can simply press Enter after typing each input value; as any white-space will act as a delimiter in C. For an instance, to take n integers as an input, one may write something like this: for (i=1; i<=n; i++) {

How to input 2 numbers in C?

printf("Enter two integers: "); scanf("%d %d", &number1, &number2); Then, these two numbers are added using the + operator, and the result is stored in the sum variable.

How to take 2 space separated integer input in C?

Use a simple for loop. int i, n, arr[100]; scanf("%d", &n); for (i = 0; i < n; ++i) scanf("%d", &arr[i]); The above code snippet would do.


2 Answers

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.
like image 173
Ani Avatar answered Sep 23 '22 17:09

Ani


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).

like image 43
Frank Avatar answered Sep 21 '22 17:09

Frank