reading two integers in one line using C#

Viewed 79514

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

12 Answers

I have a much simpler solution, use a switch statement and write a message for the user in each case, using the Console.write() starting with a ("\n").

Here's an example of filling out an array with a for loop while taking user input. * Note: that you don't need to write a for loop for this to work* Try this example with an integer array called arrayOfNumbers[] and a temp integer variable. Run this code in a separate console application and Watch how you can take user input on the same line!

           int temp=0;
           int[] arrayOfNumbers = new int[5];

        for (int i = 0; i < arrayOfNumbers.Length; i++)
            {
      switch (i + 1)
                {
                    case 1:
                        Console.Write("\nEnter First number: ");
                        //notice the "\n" at the start of the string        
                        break;
                    case 2:
                        Console.Write("\nEnter Second number: ");
                        break;
                    case 3:
                        Console.Write("\nEnter Third number: ");
                        break;
                    case 4:
                        Console.Write("\nEnter Fourth number: ");
                        break;
                    case 5:
                        Console.Write("\nEnter Fifth number: ");
                        break;


                    } // end of switch

                    temp = Int32.Parse(Console.ReadLine()); // convert 
                    arrayOfNumbers[i] = temp; // filling the array
                    }// end of for loop 

The magic trick here is that you're fooling the console application, the secret is that you're taking user input on the same line you're writing your prompt message on. (message=>"Enter First Number: ")

This makes user input look like is being inserted on the same line. I admit it's a bit primitive but it does what you need without having to waste your time with complicated code for a such a simple task.

Related