8

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.

Vinod Rathod
  • 732
  • 3
  • 8
  • 23
  • Possible duplicate of [Swift Addition: Execution was interrupted, reason: EXC\_BAD\_INSTRUCTION (Code=EXC\_l386\_INVOP, subcode=0x0)](http://stackoverflow.com/questions/35347755/swift-addition-execution-was-interrupted-reason-exc-bad-instruction-code-exc) – Henrik Gustafsson Feb 13 '16 at 13:54
  • no its not - I'm expecting how to take STDIN in playgrounds, that question is a bit different. @HenrikGustafsson – Vinod Rathod Feb 13 '16 at 13:56
  • You can't at this stage as far as I have tested. You have to create a command line tool. Or you could create a playground with a "Singe View" add a UITextView an enter button and do it that way. :) Good luck! – uplearned.com Apr 02 '19 at 00:21

6 Answers6

7

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

MANISH PATHAK
  • 2,602
  • 4
  • 27
  • 31
4

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
EdiZ
  • 441
  • 4
  • 13
  • 2
    This is a great solution for use on sites like HackerRank when you are using a Xcode Playground to work on your code. – Mark Gerrior Jan 25 '18 at 23:33
2

Try using Optional Chaining:

if let input = readLine() {
    print("Input: \(input)")
} else {
    print("No input.")
}
Henrik Gustafsson
  • 51,180
  • 9
  • 47
  • 60
  • Obviously this will print "No input.\n" in playground. But it cannot be the answer for my question. Yes it was nice trick – Vinod Rathod Feb 13 '16 at 14:29
  • As far as I know it's not possible to use standard input from playground. This is just a way of working around the nil issue. It should work once you run it outside of playground though. – Henrik Gustafsson Feb 13 '16 at 14:43
  • can you tell me why this code works `var input = readLine()` and why not this `var input = readLine()!` in playground. – Vinod Rathod Feb 13 '16 at 14:48
  • @VinodRathod in my playground (Xcode 7.2.1) it 'runs forewer' (so readLine doesn't return) – user3441734 Feb 13 '16 at 14:49
0

Go to

New > Project > MacOs > Command Line Tool

then you can apply :

let value1: String?

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

"" for the default value

Marcy
  • 4,611
  • 2
  • 34
  • 52
0
private var lines: IndexingIterator<[String]>?

public var file: String? {
    didSet {
        lines = file?.split(separator: "\n").map(String.init).makeIterator()
    }
}

public func readLine() -> String? {
    lines?.next()
}
Roman
  • 1,309
  • 14
  • 23
-1

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.

  • no this function input() is same as readLine(). I'm concerned about how to get the standard input from user in playground – Vinod Rathod Feb 13 '16 at 13:25