Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 10, 2022 11:56 am GMT

Reading from the Standard Input (stdin) in Swift

There are many situations where we need to read input from StdIn. For instance, this is how inputs are provided in competitive programming websites such as Hackerrank.

Reading from StdIn

readLine() function is used to read the input from the user.

readLine(strippingNewLine: Bool)

Usually strippingNewLine is set to true, So that it will identify newline newline characters and character combinations are not a part of the input. Else, they will also be considered as the input.

And print() function is used to write the output to StdIn.

Reading string from StdIn

let str = readLine(strippingNewline: true)!

It will be fine to force unwrap the String if we are sure about the situation else it may leads to crash.

Reading Int from StdIn

let str = Int(readLine(strippingNewline: true)!)!

Reading array of String from StdIn

let array = (readLine(strippingNewline: true))?.split {$0 == " "}.map (String.init)print(array!)

Reading array of Int from StdIn

import Foundationvar arr = readLine()!.components(separatedBy: " ").map{ (a: String)->(Int) in    return Int(a)!}print(array!)

Testing

readline() returns nil in Playgrounds. So, in order to use this function we need to create Command Line Tool application.

File -> New -> Project.. (or simply N) -> macOS -> Command Line Tool.

After creating the project we can use it just as Playgrounds.


Original Link: https://dev.to/rithvik78/reading-from-the-standard-input-stdin-in-swift-19n6

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To