Jump to content
  • Advertisement
Sign in to follow this  

Reading Integers from a Text File

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

If you intended to correct an error in the post then please contact us.

Recommended Posts



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

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,




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 this post

Link to post
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 this post

Link to post
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.


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

Edited by unbird

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!