How to take STDIN in Swift playground

跟風遠走 提交于 2020-04-04 09:11:24

问题


I know that to program in STDIN and STDOUT, we need to make an command line project in Xcode. But how do I take a standard input in playground.

Whenever I try to run such code in playground

var input = readLine()!

I always get this error

Execution was interrupted, reason: EXC_BAD_INSTRUCTION (Code=EXC_l386_INVOP, subcode=0x0)

Is it possible to take STDIN in playground or not?

UPDATE

I know this error is because of nil input variable but want to know how to overcome this nil value.


回答1:


Fixed Solution for SWIFT 3

To make it work, Create a new command line tool project.

Go to "File" -> "New" -> "Project" -> "macOS" -> "Command Line Tool".

import Foundation

print("Hello, World!")


func solveMefirst(firstNo: Int , secondNo: Int) -> Int {
    return firstNo + secondNo
}

func input() -> String {
    let keyboard = FileHandle.standardInput
    let inputData = keyboard.availableData
    return NSString(data: inputData, encoding:String.Encoding.utf8.rawValue) as! String
}

let num1 = readLine()
let num2 = readLine()

var IntNum1 = Int(num1!)
var IntNum2 = Int(num2!)

print("Addition of numbers is :  \(solveMefirst(firstNo: IntNum1!, secondNo: IntNum2!))")

And run the project using CMD + R




回答2:


Playground can not read an input from the commend line.

You can use a custom "readLine()" function and a global input variable, each element in the input array is presenting a line:

import Foundation

var currentLine = 0
let input = ["5", "5 6 3"]

func readLine() -> String? {
    if currentLine < input.endIndex {
        let line = input[currentLine]
        currentLine += 1
        return line
    } else {
        return nil
    }
}

let firstLine = readLine() //  5
let secondLine = readLine() // 5 6 3
let thirdLine = readLine() // nil



回答3:


Try using Optional Chaining:

if let input = readLine() {
    print("Input: \(input)")
} else {
    print("No input.")
}



回答4:


For getting input from command line, like Console.ReadLine... Chalkers has a solution as follows.

func input() -> String {
    var keyboard = NSFileHandle.fileHandleWithStandardInput()
    var inputData = keyboard.availableData
    return NSString(data: inputData, encoding:NSUTF8StringEncoding) as! String
}

please ask for further if it doesn't work Vinod.




回答5:


Go to

New > Project > MacOs > Command Line Tool

then you can apply :

let value1: String?

value1 = readLine()
print(value ?? "")

"" for the default value



来源:https://stackoverflow.com/questions/35380343/how-to-take-stdin-in-swift-playground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!