SML / NJ从文件中读取下一个字符,忽略空格

时间:2014-08-11 19:03:36

标签: input character smlnj

你能给我一个解决方案来创建一个函数来读取文件流中的下一个字符,忽略空格吗? (在SML / NJ)。

1 个答案:

答案 0 :(得分:0)

您需要使用以下库:

Char满足您的空白需求。

Text_IO了解您的流媒体需求。

以下代码是一个示例,这不是我最好的代码:)

let 
    (* Use TextIO library to open instream to file *)
    val ins = TextIO.openIn("C:\\Test.txt")

    (* This function takes the instream, and repeats 
        calling itself untill we are the end of the file *)
    fun handleStream (ins : TextIO.instream) =
        let 
            (* Read one character, hence the name, input1*)
            val character = TextIO.input1 (ins)

            (* This function decides whether to close the stream
                or continue reading, using the handleStream function 
                recursively.
            *)
            fun helper (copt : char option) =
                case copt of 
                    (* We reached the end of the file*)
                    NONE => TextIO.closeIn(ins)
                    (* There is something! *)
                  | SOME(c) => 
                        ((if (Char.isSpace c) 
                            then
                                (*ignore the space*)
                                ()
                            else
                                (* Handle the character c here *)
                                ())
                        (* Recursive call *)
                        ; handleStream(ins))
        in
            (* start the recursion *)
            helper (character)
        end
in
    (* start handling the stream *)
    handleStream( ins )
end