Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

parsing - reading two integers in one line using C#

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...