reading two integers in one line using C#

前端 未结 12 1685
旧巷少年郎
旧巷少年郎 2020-11-30 09:37

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


        
12条回答
  •  迷失自我
    2020-11-30 10:20

    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.

提交回复
热议问题