Read numbers from a text file in C#

前端 未结 7 1244
别那么骄傲
别那么骄傲 2020-12-14 18:21

This is something that should be very simple. I just want to read numbers and words from a text file that consists of tokens separated by white space. How do you do this in

相关标签:
7条回答
  • 2020-12-14 18:45

    Here is my code to read numbers from the text file. It demonstrates the concept of reading numbers from text file "2 3 5 7 ..."

    public class NumberReader 
    {
        StreamReader reader;
    
        public NumberReader(StreamReader reader)
        {
            this.reader = reader;
        }
    
        public UInt64 ReadUInt64()
        {
            UInt64 result = 0;
    
            while (!reader.EndOfStream)
            {
                int c = reader.Read();
                if (char.IsDigit((char) c))
                {
                    result = 10 * result + (UInt64) (c - '0');
                }
                else
                {
                    break;
                }
            }
    
            return result;
        }
    }
    

    Here is sample code to use this class:

    using (StreamReader reader = File.OpenText("numbers.txt"))
    { 
        NumberReader numbers = new NumberReader(reader);
    
        while (! reader.EndOfStream)
        {
            ulong lastNumber = numbers.ReadUInt64();
        }
    }
    
    0 讨论(0)
提交回复
热议问题