【发布时间】:2019-10-25 09:09:15
【问题描述】:
首先,我在一个文本文件中有一组随机浮点数,我已经成功地制作了一个能够在编译后从文本文件中读取数字的代码。现在我需要创建一个数字范围并从文本文件中删除范围之外的数字,并且只将数字保留在文本文件内的范围内。例如,我想只保留 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();
}
}
}
【问题讨论】:
-
除了需要将
Write替换为WriteLine,并且必须在每一行上按回车/回车键(由于Console.ReadLine()的位置,您的代码可以像您一样工作期望,并且文件不是空的。您能否详细解释一下您所面临的问题?调试时会发生什么? -
你需要删除
Console.ReadLine(); -
致 Chetan 先生,如果我这样做会出现错误:System.FormatException: 'Input string was not in a correct format.'
-
@user 请参阅 TheGeneral 的回答,第 3 点。您可能正在阅读空行或其他内容,而空行不是
double。 -
好的,约翰先生,我会进一步调查的
标签: c#