这是作业。目前正在使用二进制文件访问;我正在尝试从文本文件中读取int类型的数据。我需要计算数据中的平均值,高/低值和#值。我有一个从文件中检索和显示数据的方法,但我不知道如何存储/使用文件中的值进行计算。数据文件有20个int类型的值。
这是我到目前为止所得到的。
static void Main(string[] args)
{
/* Initializing FileStream and BinaryReader
* for file access and reading int data from file
*/
FileStream filStream;
BinaryReader binReader;
//Instructions to user to open specific data file
Console.WriteLine("Enter IntData.txt for name of file: ");
string fileName = Console.ReadLine();
try
{
filStream = new FileStream(fileName, FileMode.Open,
FileAccess.Read);
binReader = new BinaryReader(filStream);
RetrieveAndDisplayData(binReader);
//Declared array for possible calculations
int[] numbers = new int[20];
for (int i = 0; i < numbers.Length; i++)
{
//Numbers from file go here
//How to fill array with data values from file?
}
binReader.Close();
filStream.Close();
}
//Exception Handling
catch (FileNotFoundException exc)
{
Console.WriteLine(exc.Message);
}
catch (InvalidDataException exc)
{
Console.WriteLine(exc.Message);
}
catch (EndOfStreamException exc)
{
Console.WriteLine(exc.Message);
}
catch (IOException exc)
{
Console.WriteLine(exc.Message);
}
Console.ReadKey();
}
public static void RetrieveAndDisplayData(BinaryReader binReader)
{
// Read string data from the file
Console.WriteLine(binReader.ReadString());
// Read integer data from the file
for (int i = 0; i < 11; i++)
{
Console.WriteLine(binReader.ReadInt32());
}
// Read decimal data from the file
Console.WriteLine(binReader.ReadDecimal());
}
}
}
答案 0 :(得分:0)
string filename = "....";
var content = System.IO.File.ReadAllText(filename);
var arr = content.Split("\n");
var intArr = arr.Select(x=> int.Parse(x)).ToArray(); // will return arr as int
给出像
这样的文本文件输入1
2
3
*代码未经过验证,如果工作失败,我会稍后再做。
答案 1 :(得分:0)
从文件到数组的商店数据尝试更改您的代码
...
filStream = new FileStream(fileName, FileMode.Open,
FileAccess.Read);
binReader = new BinaryReader(filStream);
//Declared array for possible calculations
int[] numbers = new int[20];
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = binReader.ReadInt32();
}
...