arthankamal
arthankamal

Reputation: 6413

Swift two readLine/scanf/stdin input in Single line

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();

Like
10 20

Upvotes: 3

Views: 3180

Answers (3)

Yang_____
Yang_____

Reputation: 213

import Foundation

let text: String = readLine()! // input "1 2 3" in the console
let result: [Int] = text.split(separator: " ").map { Int($0)! } // [1, 2, 3]
print(result)

Use split() to separate the return value of readLine() and convert [String] to [Int] using map().

Upvotes: 1

arthankamal
arthankamal

Reputation: 6413

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)

Upvotes: 2

Cœur
Cœur

Reputation: 38667

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

Upvotes: 4

Related Questions