简体   繁体   中英

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

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

在@Cœur的帮助下,我将其编写如下,以便在HackerRank的同一行上获得两个输入

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

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

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