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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With