[英]an unknown size array in c#
我正在用C#編程,我想定義一個我不知道其大小的數組,因為我想從文件中讀取內容,而我不知道該文件中的元素數量。 這是我的代碼,“ x”數組有問題!
using (TextReader reader = File.OpenText("Numbers.txt"))
{
string[] bits;
string text = reader.ReadLine();
int i ,j=0;
int [] x;
while (text != null)
{
i = 0;
bits = text.Split(' ');
while (bits[i] != null)
{
x[j] = int.Parse(bits[i]);
i++;
j++;
}
text = reader.ReadLine();
}
}
之后,我將收到此錯誤“使用未分配的局部變量'x'”,我不知道該怎么辦! 請幫我...
之所以收到該錯誤,是因為您沒有初始化變量(除非知道要存儲在其中的項目數量,否則您實際上無法做到)。
由於您不知道商品數量,因此應該改用List
,它可以根據商品數量動態縮放:
using (TextReader reader = File.OpenText("Numbers.txt"))
{
string[] bits;
string text = reader.ReadLine();
int i;
IList<int> x = new List<int>();
while (text != null)
{
i = 0;
bits = text.Split(' ');
while (bits[i] != null)
{
x.Add(int.Parse(bits[i]));
i++;
}
text = reader.ReadLine();
}
}
對於一個甜蜜的單線:
int[] x = File
.ReadAllLines("Numbers.txt")
.SelectMany(s => s.Split(' ').Select(int.Parse))
.ToArray();
為了減少內存占用,請考慮以下替代方法:
public static IEnumerable<int> ReadNumbers()
{
using (var reader = new StreamReader(File.OpenRead("Numbers.txt."))) {
string line;
while ((line = reader.ReadLine()) != null) {
foreach (var number in line.Split(' ')) {
yield return int.Parse(number);
}
}
}
}
當心,每次您遍歷ReadNumbers
的結果時,都會讀取該文件。 除非號文件是非常大的,第一個解決方案是遠遠優於。
問題出在這一行:
int [] x;
您為什么不只列出一個簡單的清單?
List<int> myIntList = new List<int>();
您可以添加以下項目:
myIntList.Add(1);
然后像這樣遍歷它:
foreach(int item in myIntList)
{
Console.WriteLine(item);
}
正如其他人所說,您需要使用列表。 除了已說過的話,您還應該同時處理IO錯誤和壞數據,這是最佳做法。 這可能對您正在做的事情來說是過大的,但是最好養成這種習慣。
try
{
List<int> x = new List<int>();
using (TextReader reader = File.OpenText("Numbers.txt"))
{
string text;
while ((text = reader.ReadLine()) != null)
{
string[] bits = text.Split(' ');
foreach (string bit in bits)
{
// If you're parsing a huge file and it happens to have a
// decent bit of bad data, TryParse is much faster
int tmp;
if(int.TryParse(bit, out tmp))
x.Add(tmp);
else
{
// Handle bad data
}
}
}
}
}
catch (Exception ex)
{
// Log/handle bad text file or IO
}
這里已經有一些不錯的答案,但是只是為了好玩:
using (var reader = File.OpenText("Numbers.txt"))
{
var x = new List<int>();
var text = reader.ReadLine();
while (text != null)
{
x.AddRange(text.Split(' ').Select(int.Parse));
text = reader.ReadLine();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.