我有以下代碼從文件OCaml的讀 n字符
let read_file filename =
let lines = ref [] in
let chan = open_in filename in
try
while true do
lines := input_line chan :: !lines
done;
!lines
with End_of_file ->
close_in chan;
List.rev !lines
讀線。然而,該代碼添加了額外的「\」字符「\ n」。
E.g.
helloworld\n
被讀入
helloworld\\n
我應如何關閉這讓我得到helloworld\n
呢?
非常感謝!
編輯
所以我跟這個測試:
let read_file filename =
let lines = ref [] in
let chan = open_in filename in
try
while true do
lines := input_line chan :: !lines
done;
!lines
with End_of_file ->
close_in chan;
List.rev !lines
let() =
let lines = read_file "test.txt" in
for i=1 to List.length lines
do
Printf.printf("%s") (List.nth lines (i-1))
done;
的test.txt
helloworld\n
輸出是helloworld\n
而不是helloworld
用一個新行。
感謝您的幫助。是的,我得到了同樣的結果。我可能誤解了這個錯誤,但是我想讓「helloworld \ n」這樣,當我運行print時,它會打印出「helloworld」和一個新行,而不是「\ n」。 – Ra1nWarden
這就是打印字符串時會執行的操作。它只是頂級顯示額外的反斜槓(以消除解釋REPL結果時的不明確性)。 –
嗯。我想在打印輸出時將'\ n'渲染爲新行...... – Ra1nWarden