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

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

问题描述

这是一件应该很简单。我只是想从一个包含由空格分隔的标记文本文件中读取数字和文字。你如何在C#这样做吗?例如,在C ++中,下面的代码将努力读取整数,浮点数和字。我不希望有使用正则表达式或写任何特殊的解析代码。

  ifstream的中(file.txt的 ); 
INT int_val;
浮动float_val;
串string_val;
&中的GT;> int_val>> float_val>> string_val;
in.close();



另外,每当一个令牌被读出,不超过一个的字符以外的令牌应该被读入。这允许进一步文件读取取决于被读出的标记的值。作为一个具体的例子,考虑

 字符串决胜局; 
INT大小;
字符串名称;

&中的GT;>决胜局;
如果(决胜局==名称)$ B $在B>>名称;
,否则如果(决胜局==大小)在
>>尺寸;
,否则如果(decider.empty()及!&放大器;判定[0] =='#')
read_remainder_of_line(上);



解析二进制PNM文件也是为什么你想停止阅读文件作为一个很好的例子一旦一个完整的令牌被读入。


解决方案

布兰农的回答解释了如何阅读的二进制的数据。如果你想读的文本的数据,你应该阅读的字符串,然后把它们解析 - 对于其中有内置的方法,当然,



例如,要读取数据的文件:

  10 
10.5
你好

您可以使用:

 使用(TextReader的读者= File.OpenText(的test.txt))
{
INT X = int.Parse(reader.ReadLine());
双Y = double.Parse(reader.ReadLine());
串Z = reader.ReadLine();
}



请注意,这没有任何错误处理。在尤其是,它会引发异常,如果该文件不存在,前两行有不适当数据,或有小于两行。它会留在以Z 的值,如果该文件只有两行。



有关后者可能无法更优雅更强大的解决方案,你会想检查是否 reader.ReadLine()返回(指示文件末尾),并使用 int.TryParse double.TryParse 而不是解析方法。



这是假设有值之间的行分隔符。如果你真的想读这样的字符串:

  10 10.5你好
<使用

 :/ pre> 

那么代码将是非常相似(读者的TextReader = File.OpenText(的test.txt))
{
字符串文本= reader.ReadLine();
的String []位= text.Split('');
INT X = int.Parse(位[0]);
双Y = double.Parse(位[1]);
串Z =位[2];
}



同样,你要进行适当的错误检测和处理。请注意,如果文件真的只是一个由单行的,你可能需要使用 File.ReadAllText 来代替,使其稍微简单。还有 File.ReadAllLines 它读取整个文件到线的字符串数组



编辑:如果您需要通过的任何的空白,那么你很可能是最好的分裂出去读取整个文件, File.ReadAllText ,然后使用正则表达式来拆分它。 。在这一点上我想知道你代表包含空格的字符串



在我的经验,你通常知道的比这更多的格式 - 是否会有一个行分隔符或用空格分隔同一行等多个值。



我也补充一点,混合二进制/文本格式一般都是不愉快的处理。简单而有效的文本处理趋于读入缓冲区,这成为问题,如果有二进制数据为好。如果你需要在一个二进制文件中的文本部分,它通常是最好的,包括长度前缀,这样只是一块数据进行解码。


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.

解决方案

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

You might use:

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

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.

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

then the code would be very similar:

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];
}

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.

EDIT: 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天全站免登陆