从 C# 中的文本文件中读取数字 [英] Read numbers from a text file in C#

查看:41
本文介绍了从 C# 中的文本文件中读取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该很简单.我只想从由空格分隔的标记组成的文本文件中读取数字和单词.你如何在 C# 中做到这一点?例如,在 C++ 中,以下代码将用于读取整数、浮点数和单词.我不想使用正则表达式或编写任何特殊的解析代码.

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

解析二进制 PNM 文件也是一个很好的例子,说明为什么您希望在读入完整令牌后立即停止读取文件.

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.

推荐答案

Brannon 的回答解释了如何读取二进制数据.如果您想读取 text 数据,您应该读取字符串然后解析它们 - 当然有内置方法.

Brannon's answer explains how to read binary data. If you want to read text data, you should be reading strings and then parsing them - for which there are built-in methods, of course.

例如读取包含数据的文件:

For example, to read a file with data:

10
10.5
hello

您可能会使用:

using (TextReader reader = File.OpenText("test.txt"))
{
    int x = int.Parse(reader.ReadLine());
    double y = double.Parse(reader.ReadLine());
    string z = reader.ReadLine();
}

注意这里没有错误处理.特别是如果文件不存在,前两行有不适当的数据,或者少于两行,它会抛出异常.如果文件只有两行,它会在 z 中留下 null 的值.

Note that this has no error handling. In particular, it will throw an exception if the file doesn't exist, the first two lines have inappropriate data, or there are less than two lines. It will leave a value of null in z if the file only has two lines.

对于可以更优雅地失败的更强大的解决方案,您需要检查 reader.ReadLine() 是否返回 null(指示文件结尾)和使用 int.TryParsedouble.TryParse 而不是 Parse 方法.

For a more robust solution which can fail more gracefully, you would want to check whether reader.ReadLine() returned null (indicating the end of the file) and use int.TryParse and double.TryParse instead of the Parse methods.

假设值之间有一个行分隔符.如果你真的想读取这样的字符串:

That's assuming there's a line separator between values. If you actually want to read a string like this:

10 10.5 hello

那么代码将非常相似:

using (TextReader reader = File.OpenText("test.txt"))
{
    string text = reader.ReadLine();
    string[] bits = text.Split(' ');
    int x = int.Parse(bits[0]);
    double y = double.Parse(bits[1]);
    string z = bits[2];
}

同样,您需要执行适当的错误检测和处理.请注意,如果文件真的只包含一行,您可能需要使用 File.ReadAllText 来代替,使其稍微简单一些.还有 File.ReadAllLines 将整个文件读入一个由行组成的字符串数组.

Again, you'd want to perform appropriate error detection and handling. Note that if the file really just consisted of a single line, you may want to use File.ReadAllText instead, to make it slightly simpler. There's also File.ReadAllLines which reads the whole file into a string array of lines.

如果您需要按任何空格分割,那么您可能最好使用 File.ReadAllText 读取整个文件,然后使用正则表达式拆分它.那时我确实想知道您如何表示包含空格的字符串.

If you need to split by any whitespace, then you'd probably be best off reading the whole file with File.ReadAllText and then using a regular expression to split it. At that point I do wonder how you represent a string containing a space.

根据我的经验,您通常比这更了解格式 - 是否会有行分隔符,或者同一行中的多个值由空格等分隔.

In my experience you generally know more about the format than this - whether there will be a line separator, or multiple values in the same line separated by spaces, etc.

我还要补充一点,混合的二进制/文本格式通常很难处理.简单而高效的文本处理往往会读入缓冲区,如果还有二进制数据,这就会成为问题.如果您需要二进制文件中的文本部分,通常最好包含一个长度前缀,以便可以解码该段数据.

I'd also add that mixed binary/text formats are generally unpleasant to deal with. Simple and efficient text handling tends to read into a buffer, which becomes problematic if there's binary data as well. If you need a text section in a binary file, it's generally best to include a length prefix so that just that piece of data can be decoded.

这篇关于从 C# 中的文本文件中读取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆