I'm taking a course with a hands-on question on Swift programming, that redirect me to Hackerrank
Write a function named printMessage that takes two parameters - a string message and an integer count. The message should print and repeat the message as specified in the count parameter.
Message:"Hello , How are You"
For instance take Count as 8
This should print Message:"Hello , How are You" 8 times consecutively.
The problem is when I submit my code always said Wrong answer, then I tried with custom input, and it throws me no response on STDOUT. Anyone knows what's wrong?
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)
The error probably comes from a scenario where the program is receiving the wrong type of input - not an integer. The line above reads all the remaining characters on the current line and advances to the next line.
You have no output because you never called the function. A tutorial will clear up this issue and several more that you haven't yet encountered.
This is the standard stream to write or print the output from your code. For example, for the above-mentioned coding question, you need to write the output from your program.
I have run into this before, the way I solved it was saving my code somewhere and resetting to the boilerplate code. So just reset to the boilerplate and copy your function back in. On many swift hackerrank problems they have something like the following:
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)!)
The code after the function is what writes to stdout
Hackerrank in some swift exercises fires that message whenever you have a buffer overflow, instead of warning you about it
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