Question: Swift two readLine/scanf/stdin input in Single line


Swift two readLine/scanf/stdin input in Single line

Answers 2
Added at 2016-12-24 08:12

Is there anyway in swift we can get two inputs in single line.?

Like C
scanf("%d %d", &valueOne, &valueTwo);

so i can enter 10 20

But in swift, I can read only one input in one line, using readLine
let valueOne = readLine(); let valueTwo = readLine();

10 20

nr: #1 dodano: 2016-12-24 09:12

You can easily split what is read into an Array.

let values = readLine()?.components(separatedBy: CharacterSet.whitespacesAndNewlines) ?? []

You can then store those in multiple variables in different ways. Here is an example:

let valueOne = values.count > 0 ? Int(values[0]) : nil
let valueTwo = values.count > 1 ? Int(values[1]) : nil
nr: #2 dodano: 2016-12-26 06:12

With the help of @Cœur, I wrote it as below, to get two inputs on same line in HackerRank

let values = readLine()?.characters.split(" ").flatMap(String.init)

Source Show
◀ Wstecz