删除范围外的浮点数,并将数字保留在文本文件的范围内

时间:2019-06-11 01:29:23

标签: c#

首先,我在文本文件中有一组随机浮点数,我成功编写了一个代码,该代码能够在编译后从文本文件中读取数字。现在,我需要创建一个数字范围,并从文本文件中删除该范围之外的数字,而仅将数字保留在文本文件中的范围之内。举例来说,我只想保留743和1000之间的数字,并从文本文件中删除其余的数字。

请协助我处理此事。谢谢。

我尝试制作如下所示的代码,但是未显示预期的结果。编译后,我的文本文件为空,这意味着文本文件中的所有数字都将被删除。

这是我在文本文件中创建的一组随机浮点数:

743.6 
742.8
744.7
743.2
1000
1768.6
1750
1767
1780
1500

我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ReadTextFile
{
class Program
{
    static void Main(string[] args)


    {

        string usersPath = "C:\\Users\\Student\\Desktop\\ConsoleApp1\\ConsoleApp1\\Data\\TextFile.txt";

        List<string> lines = File.ReadAllLines(usersPath).ToList();

        StreamWriter writer = new StreamWriter(usersPath);
        foreach (string line in lines)
        {
            double x = double.Parse(line);

            if (x > 740.7 && x < 1500.6)
            {
                writer.Write(line);
              //Console.WriteLine(line);

            }
            Console.ReadLine();

        }
        writer.Close();

    }

}

}

1 个答案:

答案 0 :(得分:1)

问题在于您Console.ReadLine().令人讨厌,意思是,您在请求用户输入,而程序从不写行。

但是还有其他问题

  1. 您使用的是writer.Write(line);而不是writer.WriteLine(line);,这会将所有内容融合到一行中
  2. 您应该使用using语句
  3. double.Parse如果出现空白行或意外情况,将引发异常,您可以改用double.TryParse
  4. 您可以改用File.WriteAllLines
  5. 作为额外的奖励,您可以在LINQ上完成所有操作

您的固定代码

var lines = File.ReadAllLines(usersPath);

using (var writer = new StreamWriter(usersPath))
{
   foreach (var line in lines)
      if(double.TryParse(line,out var value) && value > 740.7 && value < 1500.6)
          writer.WriteLine(value);
}

或更简单的容错示例

string usersPath = $"C:\\Users\\Student\\Desktop\\ConsoleApp1\\ConsoleApp1\\Data\\TextFile.txt";


// read all lines
var lines = File.ReadAllLines(usersPath)

                 // for each line, try and and convert it double, if not return null
                .Select(x => double.TryParse(x, out var value) ? value : (double?)null)

                 // filter all nulls and values outside of the range
                .Where(x => x != null && x > 740.7 && x < 1500.6)

                 // convert each element to a string
                .Select(x => x.ToString());

// write all lines
File.WriteAllLines(usersPath, lines);

其他资源

File.ReadAllLines Method

  

打开一个文本文件,将文件的所有行读入字符串数组,   然后关闭文件。

Enumerable.Select Method

  

将序列的每个元素投影为新形式。

Double.TryParse Method

  

将数字的字符串表示形式转换为其双精度   等效的浮点数。返回值指示是否   转换成功还是失败。

Enumerable.Where Method

  

根据谓词过滤一系列值。

File.WriteAllLines Method

  

创建一个新文件,向该文件写入一个或多个字符串,然后   关闭文件。