Reading Integers from a Text File

Started by
1 comment, last by unbird 9 years, 4 months ago

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)
  4. append the value at StreamReader.Read() to the string builder
  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()))
{
       sb.Append((char)sr.Read());
}

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

Please ask if you need any more information.

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?

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

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

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.

Edit: Reading helps, sorry. You're already using a StreamReader.

This topic is closed to new replies.

Advertisement