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
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++) {
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.
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.
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:
int.TryParse
to attempt to parse the strings into numbers. 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With