• 13
• 18
• 19
• 27
• 10

Reading Integers from a Text File

This topic is 1213 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hello,

I am working on an exercise for C# that involves reading from a Text file, extracting any Integer values (+ or -) and displaying them in the console window, in a tabular format.

On a 'one value per line' basis, I have managed to accomplish this. My code runs through the text file, ignores any decimals or non-numeric characters (NNC), and outputs Integers into a table.

I want to make this a bit more robust, the exercise never specifies how text in the file should be laid out, so I want to assume that having multiple Integers, Decimals/NNC on the same line can be accounted for. These would be separated by Whitespace.

My pseudo-code would be as follows:

1. while Not at the end of the Stream
2. create a StringBuilder
3. while StreamReader.Peek is not a whitespace or null (should break on detecting whitespace)
5. Try to parse this new string to an integer data type for output later.
6. Repeat

My issue stems from points 3 and 4, the inner loop. Peek doesn't seem to recognise a whitespace value and the loop won't break.

while (!String.IsNullOrWhiteSpace(sr.Peek().ToString()))
{
}

sr is the StreamReader object. Is there something I'm missing here, or am I making it too hard on myself?

Many thanks,

Stitchs.

Update: I have stepped through the StringBuilder every time it is appended too, and have also found out that Read is also taking the \n and \r escape sequences into account. How would I account for these?

Edited by stitchs

Share on other sites
You cast the return value of Read to Char, but you don't cast the return value of Peek to Char before converting it to a string. I suspect that is causing you some of your issues.

Share on other sites

To easily handle newlines rather use the StreamReader, which has a ReadLine method. Then have a look at String.Split, in particular the overloads with StringSplitOptions.