简体   繁体   中英

How do I ignore every input after the first few characters in the console in C#?

class Program
    {
        static void Main(string[] args)
        {
            var information= Console.ReadLine();
            var one= Int32.Parse(informatie.Split(' ')[0]);
            var two = Int32.Parse(informatie.Split(' ')[1]);
        }
    }

I want the user to input the following: two numbers, seperated by a whitespace, so, for example: 5 2

After that, I want to be able to catch the first number in var one and the second one in var two. How can I make this program such that everything which comes after the 2 will be ignored? Right now, if I add anything else after the 2, the program crashes.

You can get the characters by index, then use Char.GetNumericValue to convert to int :

var one = (int)Char.GetNumericValue(informatie[0]);
var two = (int)Char.GetNumericValue(informatie[2]);

Of course you should also validate the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM