Emil
Emil

Reputation: 31

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

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?

Upvotes: 2

Views: 793

Answers (3)

Emil
Emil

Reputation: 31

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!

Upvotes: 1

Luaan
Luaan

Reputation: 63732

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).

Upvotes: 2

Mark Seemann
Mark Seemann

Reputation: 233150

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

Upvotes: -1

Related Questions