如何在Swift游乐场玩STDIN [英] How to take STDIN in Swift playground

查看:149
本文介绍了如何在Swift游乐场玩STDIN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道要在STDIN和STDOUT中编程,我们需要在Xcode中创建一个命令行项目。
但是如何在操场上取标准输入。

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

我总是收到此错误


执行被中断,原因:EXC_BAD_INSTRUCTION
(代码= EXC_l386_INVOP,子代码= 0x0)

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

是是否可以在游乐场参加STDIN?

Is it possible to take STDIN in playground or not?

更新

我知道这个错误是因为 nil 输入变量,但想知道如何克服这个nil值。

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

推荐答案

SWIFT 3的固定解决方案

要使其正常工作,请创建新命令行工具项目。

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

转到文件 - >新建 - >项目 - >macOS - >命令行工具。

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!))")

使用 CMD + R运行项目

这篇关于如何在Swift游乐场玩STDIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆