首页 > 解决方案 > HackerRank 说~stdout 上没有响应~Swift

问题描述

我正在上一门关于 Swift 编程的实践问题课程,这会将我重定向到 Hackerrank

编写一个名为 printMessage 的函数,它接受两个参数——一个字符串消息和一个整数计数。该消息应打印并重复 count 参数中指定的消息。

消息:“你好,你好吗”

例如将 Count 设为 8

这应该连续打印 8 次 Message:"Hello , How are You"。

问题是当我提交我的代码时总是说错误的答案,然后我尝试使用自定义输入,它在 STDOUT 上没有任何响应。有谁知道出了什么问题?

import Foundation 

func printMessage(message: String, count: Int) {

    for _ in 0..<count {
        print(message)

    }
}

let message: String = readLine()!
let count: Int = Int(readLine()!)!
printMessage(message: message, count: count)

标签: swift

解决方案


我之前遇到过这个问题,我解决它的方法是将我的代码保存在某个地方并重置为样板代码。因此,只需重置为样板并将您的函数复制回来。在许多 swift hackerrank 问题上,它们具有以下内容:

func myFunc(param: [Int]) -> [Int] {
    /*
    * Write your code here.
    */
}

// The following is an example of your function being written to stdout

let fileName = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: fileName, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: fileName)!

let result = myFunc(param: input)

fileHandle.write(result.map{ String($0) }.joined(separator: "\n").data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)

函数后面的代码是写入标准输出的


推荐阅读