如何将.txt文件中的数字读取为整数数组? [英] How to read numbers in a .txt file to an integer array?
问题描述
我有一个文件需要保存为数组.我正在尝试使用 StreamReader
将文本文件转换为整数数组.我只是不确定要在代码末尾的for循环中放入什么.
I have a file that I need to save as an array. I am trying to convert a text file to an integer array using StreamReader
. I just am unsure as to what to put in the for loop at the end of the code.
这是我到目前为止所拥有的:
This is what I have so far:
//Global Variables
int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//code to load the numbers from a file
OpenFileDialog fd = new OpenFileDialog();
//open the file dialog and check if a file was selected
if (fd.ShowDialog() == DialogResult.OK)
{
//open file to read
StreamReader sr = new StreamReader(fd.OpenFile());
int Records = int.Parse(sr.ReadLine());
//Assign Array Sizes
Original = new int[Records];
int[] OriginalArray;
for (int i = 0; i < Records; i++)
{
//add code here
}
}
.txt文件为:
5
6
7
9
10
2
PS我是一个初学者,所以我的编码技能非常基础!
PS I am a beginner, so my coding skills are very basic!
更新:我以前有使用 Line.Split
然后将文件映射到数组的经验,但是显然这不适用于这里,所以我现在该怎么办?
UPDATE: I have previous experience using Line.Split
and then mapping file to arrays but obviously that does not apply here, so what do I do now?
//as continued for above code
for (int i = 0; i < Records; i++)
{
int Line = int.Parse(sr.ReadLine());
OriginalArray = int.Parse(Line.Split(';')); //get error here
Original[i] = OriginalArray[0];
}
推荐答案
您应该能够使用与其上方相似的代码:
You should just be able to use similar code to what you had above it:
OriginalArray[i] = Convert.ToInt32(sr.ReadLine());
每次调用 sr.ReadLine
时,它都会将数据指针增加1行,从而遍历文本文件中的数组.
Every time the sr.ReadLine
is called it increments the data pointer by 1 line, hence iterating through the array in the text file.
这篇关于如何将.txt文件中的数字读取为整数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!