Why does my StreamReader.ReadLine () in F# not read \n as a new line?

丶灬走出姿态 提交于 2020-01-04 05:26:37

问题


I am currently trying to read a file as this:

53**7****\n6**195***\n*98****6*\n8***6***3\n4**8*3**1\n7***2***6\n*6****28*\n***419**5\n****8**79\n

And write it into the screen, but with new lines instead of the /n.

On the msdn description of the method StreamReader.ReadLine () it says that: A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed. The returned value is null if the end of the input stream is reached.

Why does my program not interpret \n as a new line?


回答1:


Well, the problem is that the documentation for ReadLine is talking about the '\n' (single) character, while you actually have a "\\n" two-character string.

In C#, \ is used as an escape character - for example, \n represents the character with ASCII value of 10. However, files are not parsed according to C# rules (that's a good thing!). Since your file doesn't have the literal 10-characters, they aren't interpreted as endlines, and rightly so - the literal translation in ASCII would be (92, 110).

Just use Split (or Replace), and you'll be fine. Basically, you want to replace "\\n" with "\n" (or better, Environment.NewLine).




回答2:


I used @Mark Seemann's method by letting let s = inputStream.ReadToEnd () and thereby importing the string you are typing in directly. I am able to print out the same output as you with your do-while loop, but i have to use this recursive printFile method:

let rec printFile (reader : System.IO.StreamReader) = if not(reader.EndOfStream) then let line = reader.ReadLine () printfn "%s" line printFile reader

This however does not recognize the \n as new lines - do you know why as i see the methods as very similar? Thanks!




回答3:


I can't reproduce the issue. This seems to work fine:

let s = "53**7****\n6**195***\n*98****6*\n8***6***3\n4**8*3**1\n7***2***6\n*6****28*\n***419**5\n****8**79\n"

open System.IO

let strm = new MemoryStream()
let sw = new StreamWriter(strm)
sw.Write s
sw.Flush ()
strm.Position <- 0L

let sr = new StreamReader(strm)
while (not sr.EndOfStream) do
    let line = sr.ReadLine ()
    printfn "%s" line

This prints

53**7****
6**195***
*98****6*
8***6***3
4**8*3**1
7***2***6
*6****28*
***419**5
****8**79


来源:https://stackoverflow.com/questions/33474402/why-does-my-streamreader-readline-in-f-not-read-n-as-a-new-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!