Sign in to follow this  

Reading Integers from a Text File

This topic is 1122 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

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?

Edited by stitchs

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

This topic is 1122 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this