reading two integers in one line using C#

2019-01-07 21:16发布

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条回答
贼婆χ
2楼-- · 2019-01-07 21:24
string[] values = Console.ReadLine().Split(' ');
int x = int.Parse(values[0]);
int y = int.Parse(values[1]);
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-07 21:31

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);
查看更多
We Are One
4楼-- · 2019-01-07 21:31

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.

查看更多
Emotional °昔
5楼-- · 2019-01-07 21:33

Try this:

string numbers= Console.ReadLine();

string[] myNumbers = numbers.Split(' ');

int[] myInts = new int[myNumbers.Length];

for (int i = 0; i<myInts.Length; i++)
{
    string myString=myNumbers[i].Trim();
    myInts[i] = int.Parse(myString);
}

Hope it helps:)

查看更多
在下西门庆
6楼-- · 2019-01-07 21:34

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.
查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-07 21:34

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]);
查看更多
登录 后发表回答