【发布时间】:2019-03-08 21:45:39
【问题描述】:
我正在尝试使用 StreamReader 并从文本文件中获取数据并将其存储到数组中。我有一个问题,我认为修复很简单,但我很难过。当我打印数组时,它会打印 txt 文件中的每个标记,而不是包含搜索名称的单行数据以及 11 个 int 标记。 Long_Name.txtsample
public class SSA
{
public void Search()
{
Console.WriteLine("Name to search for?");
string n = Console.ReadLine();
Search(n, "Files/Names_Long.txt");
}
public int[] Search(string targetName, string fileName)
{
int[] nums = new int[11];
char[] delimiters = { ' ', '\n', '\t', '\r' };
using (TextReader sample2 = new StreamReader("Files/Exercise_Files/SSA_Names_Long.txt"))
{
string searchName = sample2.ReadLine();
if (searchName.Contains(targetName))
{
Console.WriteLine("Found {0}!", targetName);
Console.WriteLine("Year\tRank");
}
else
Console.WriteLine("{0} was not found!", targetName);
while (searchName != null)
{
string[] tokensFromLine = searchName.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
int arrayIndex = 0;
int year = 1900;
foreach (string token in tokensFromLine)
{
int arrval;
if (int.TryParse(token, out arrval))
{
nums[arrayIndex] = arrval;
year += 10;
Console.WriteLine("{0}\t{1}", year, arrval);
arrayIndex++;
}
}
searchName = sample2.ReadLine();
}
}
return nums;
}
}
【问题讨论】:
-
把
searchName = sample2.ReadLine();放在foreach块之外,因为如果你没有完成当前(tokensFromLine),你不应该跳到文件的下一行;nums[i] = arrval;您必须在 foreach 循环的每次迭代中增加索引,而不是遍历 nums。所以在 foreach 循环之外声明 i 并在分析下一个标记之前像 i++ 一样递增它。 -
我现在得到一个:索引超出了数组异常的范围。
-
看起来不错。
for (int i = 0; i < nums.Length; i++)删除这个。您不需要为每个令牌迭代 nums 。您正在通过 arrayIndex 访问 num 的位置。 -
你是对的。在此期间,我进行了编辑,但我也忘记了这会超出索引范围。感谢您的帮助!
-
不客气
标签: c# arrays delimiter streamreader