Hello guys.
Recently, my hobby is solving algorithm problems with OCaml.
I usually use BOJ and Hacker Rank just because they have good supports for OCaml.
While solving 1152 in BOJ, I found something strange: when receiving string input, using Scanf.scanf "%[^\n]"
works fine but using read_line
gives me a runtime error on the certain test case!
For those who cannot read Korean (since the problem is described in Korean), this problem is to count the number of words in the input sentence that contains spaces. The max length of the input sentence is 1,000,000 and there are no successive spaces. Also, all words are separated by a single space.
I want to simply solve this problem as follow:
let count_words str =
let str = String.trim str in
if str = "" then 0 else (
let words = String.split_on_char ' ' str in
List.length words)
let () =
let s = read_line () in
print_int (count_words s)
But this gives me a runtime error!
However, just changing the input method from read_line
to Scanf.scanf
as follow worked just fine!
let count_words str =
let str = String.trim str in
if str = "" then 0 else (
let words = String.split_on_char ' ' str in
List.length words)
let () =
Scanf.scanf "%[^\n]" (fun s ->
print_int (count_words s)
)
Since the site does not provide the whole test cases nor the runtime error messages, so I have no clue about which input caused this error or what happened during the execution. But in my humble opinion, both methods must work fine. Am I right?
In the description about read_line
function of Pervasives documentation (whose version is the same as used for grading), it says:
Flush standard output, then read characters from standard input until a newline character is encountered. Return the string of all characters read, without the newline character at the end.
Why does read_line
give runtime error, while Scanf.scanf
works just fine?
Thank you.
PS: I know that there are more efficient and faster solutions for this problem, and I already have 28ms of satisfactory another solution as well. So please do not argue with the complexity of the algorithm used here. I just want to know why read_line
gives me a runtime error!