Read numbers from a text file in C#

2020-02-08 12:33发布

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 C#? For example, in C++, the following code would work to read an integer, float, and word. I don't want to have to use a regex or write any special parsing code.

ifstream in("file.txt");
int int_val;
float float_val;
string string_val;
in >> int_val >> float_val >> string_val;
in.close();

Also, whenever a token is read, no more than one character beyond the token should be read in. This allows further file reading to depend on the value of the token that was read. As a concrete example, consider

string decider;
int size;
string name;

in >> decider;
if (decider == "name")
    in >> name;
else if (decider == "size")
    in >> size;
else if (!decider.empty() && decider[0] == '#')
    read_remainder_of_line(in);

Parsing a binary PNM file is also a good example of why you would like to stop reading a file as soon as a full token is read in.

标签: c# file text
7条回答
你好瞎i
2楼-- · 2020-02-08 13:17

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();
    }
}
查看更多
登录 后发表回答