我试图将一个文本文件读入我的数组,但它在输出结束时添加0,直到数组的大小。我认为问题在于我阅读文本文件的方式。
我使用foreach循环来显示数组,但它做了同样的事情。
static void Main(string[] args)
{
int size = 10000;
int[] Array = new int[size];
StreamReader SR = new StreamReader("Data.Txt");
int i = 0;
while (!SR.EndOfStream)
{
Array[i] = int.Parse(SR.ReadLine());
i++;
}
Console.WriteLine("ARRAY BEFORE SORTING" );
for (int x = 0; x <= Array.Length-1 ; x++)
{
Console.WriteLine(Array[x]);
}
Console.ReadLine();
}
代码输出文本文件中的正常数字,但之后添加不必要的900 0
以下是一种简单的方法。 (还有很多其他方法可以实现这一点。您可能会找到不同的答案。我发现您使用的是基本代码块。)
问题
static void Main(string[] args)
{
int size = 10000;
int[] Array = new int[size];
您正在创建一个数组,其中10000个项目分配为0(默认值)。因此,未从文本文件中赋值的那些项将永远保持为0。
解
根据文本文件中的值数创建数组。
string[] lines = File.ReadAllLines(YOUR_FILE PATH);
int[] array = new int[lines.Length];
int i =0;
foreach(var line in lines)
{
array[i] = int.Parse(line);
i++;
}
当您在c#
中创建任何变量时,它将被初始化为预定义的默认值。
在你的情况下,int []将被分配给{0,0,0,0 .....},这意味着你有一个10000个零的数组,但你设置数字直到某个数字(低于比10000更多,所以你会得到{1,2,3,0,0,0,...}。
如果你知道之前的数组长度,你可以改变大小。或者你是一个动态阵列的List<int>
,你可以阅读所有关于它的here
这是一个使用示例
List<int> Array = new List<int>(); // must be intalized otherwise you will get null exception
using (StreamReader SR = new StreamReader("Data.Txt")) //to prevent memorey leaks
{
while (!SR.EndOfStream)
{
Array.Add(int.Parse(SR.ReadLine()));
}
}
Console.WriteLine("ARRAY BEFORE SORTING");
for (int x = 0; x <= Array.Count - 1; x++)
{
Console.WriteLine(Array[x]);
}
Console.ReadLine();
这只是因为你创建了一个大小为'10000'的数组,即使它们是空的,foreach也会在你的数组中循环10000个空元素。如果您知道元素的长度,请使用它来创建数组。否则使用List。
static void Main(string[] args)
{
List<int> array = new List<int>();
StreamReader SR = new StreamReader("Data.Txt");
while (!SR.EndOfStream)
{
array.Add(int.Parse(SR.ReadLine()));
}
Console.WriteLine("ARRAY BEFORE SORTING" );
for (int x = 0; x < array.Count; x++)
{
Console.WriteLine(array[x]);
}
Console.ReadLine();
}
你手边不知道size
,对吗?
static void Main(string[] args)
{
// File is non necessary has exactly 10000 items it can have, say, 100 ones
int size = 10000;
int[] Array = new int[size];
当你创建一个数组 - int[] Array = new int[size];
- 你已经得到它 - 10000
项目中的每一个0
;然后你重写他们的第一个9100
当最后900
仍然0
。
获得正确数组的最简单方法是Linq:
using System.Linq;
...
static void Main(string[] args)
{
int[] Array = File
.ReadLines("Data.Txt")
.Select(item => int.Parse(item))
.ToArray();
Console.WriteLine("ARRAY BEFORE SORTING");
...
如果要修改当前代码,请使用List<int>
而不是数组来收集项目:
static void Main(string[] args)
{
int size = 10000;
List<int> items = new List<int>();
// using: Do not forget to close the file (via IDisposable)
using (StreamReader SR = new StreamReader("Data.Txt"))
{
while (!SR.EndOfStream)
{
items.Add(int.Parse(SR.ReadLine()));
}
}
// Now either int[] Array = items.ToArray(); or
int[] Array = new int[items.Count]; // <- no necessary 10000
for (int i = 0; i < Array.Length; ++i)
Array[i] = items[i];
Console.WriteLine("ARRAY BEFORE SORTING");
...
您可以使用可空的int
数组。在那里,默认值将是null
,你不会在文本中附加任何0。
int size = 10000;
int?[] Array = new int?[size];