parsing - reading two integers in one line using C# -


i know how make console read 2 integers each integer self this

int = int.parse(console.readline()); int b = int.parse(console.readline()); 

if entered 2 numbers, i.e (1 2), value (1 2), cant parse integers want if entered 1 2 take 2 integers

one option accept single line of input string , process it. example:

//read line, , split whitespace array of strings string[] tokens = console.readline().split();  //parse element 0 int = int.parse(tokens[0]);  //parse element 1 int b = int.parse(tokens[1]); 

one issue approach fail (by throwing indexoutofrangeexception/ formatexception) if user not enter text in expected format. if possible, have validate input.

for example, regular expressions:

string line = console.readline();  // if line consists of sequence of digits, followed whitespaces, // followed sequence of digits (doesn't handle overflows) if(new regex(@"^\d+\s+\d+$").ismatch(line)) {    ...   // valid: process input } else {    ...   // invalid input } 

alternatively:

  1. verify input splits exactly 2 strings.
  2. use int.tryparse attempt parse strings numbers.

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -

PostgreSQL 9.x - pg_read_binary_file & inserting files into bytea -