从文本文件中读取输入,转换为int,并存储到数组中。

时间:2015-03-30 20:02:53

标签: c#

我需要一些帮助。我有一个看起来像这样的文本文件:

21,M,S,1个
22,F,M,2个
19,F,S,3
65,F,M,4个
66,M,M,4

我需要做的是将第一列放入数组int [] age中,将最后一列放入数组int []中。这是一个星期到期的大学项目。我试图解决这个问题时遇到了很多麻烦。任何帮助将不胜感激。我确实尝试过寻找答案,但没有找到我理解的任何东西。我也不能使用我们从书中学到的任何东西,所以它排除了列表<>和类似的东西。

FileStream census = new FileStream("census.txt", FileMode.Open, FileAccess.Read); 
        StreamReader inFile = new StreamReader(census);
        string input = "";

        string[] fields;
        int[] districts = new int[SIZE];
        int[] ageGroups = new int[SIZE];

        input = inFile.ReadLine();

        while (input != null)
        {
            fields = input.Split(',');


            for (int i = 0; i < 1; i++)
            {
                int x = int.Parse(fields[i]);

                districts[i] = x;

            }
            input = inFile.ReadLine();


        }
        Console.WriteLine(districts[0]);

4 个答案:

答案 0 :(得分:3)

如果你的文件只是这个,那么File.ReadAllLines()将返回一个字符串数组,每个元素都是你文件的一行。完成后,您可以使用返回数组的长度来初始化其他两个数组,数据将存储在其中。

获得字符串数组后,使用&#34;,&#34;在每个元素上调用string.Split()作为你的分隔符,现在你将有另一个字符串数组减去逗号,你将分别获取它们所需的值,它们的索引位置分别为0和3,你可以将它们存储在某个地方。您的代码看起来像这样:

//you will need to replace path with the actual path to the file.
string[] file = File.ReadAllLines("path");
int[] age = new int[file.Length];
int[] districts = new int[file.Length];
int counter = 0;

foreach (var item in file)
{
    string[] values = item.Split(',');
    age[counter] = Convert.ToInt32(values[0]);
    districts[counter] = Convert.ToInt32(values[3]);
    counter++
}

答案 1 :(得分:2)

编写此代码的正确方法:

写下您尝试执行的每一步:

// open file
// for each line 
//     parse line

然后改进“解析线”

// split by fields
// parse and handle age
// parse and handle gender
// parse and handle martial status
// parse and handle ....

然后开始编写缺失的代码。

此时你应该弄清楚迭代单个记录的字段不会对你有任何好处,因为所有字段都有不同的含义。

因此,您需要删除for并将其替换为逐字段解析/分配。

答案 2 :(得分:0)

不是循环遍历所有字段,只需参考字段的实际索引:

错:

for (int i = 0; i < 1; i++)
{
    int x = int.Parse(fields[i]);
    districts[i] = x;
}

右:

districts[i] = int.Parse(fields[0]);
ageGroups[i] = int.Parse(fields[3]);
i++;

答案 3 :(得分:0)

所以我只是做了一些BS去做你想要的。我不同意它,因为我讨厌直接硬编码进行拆分,但由于你不能使用列表,这就是你得到的:

FileStream census = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader inFile = new StreamReader(census);

int[] districts = new int[1024];
int[] ageGroups = new int[1024];
int counter = 0;

string line;
while ((line = inFile.ReadLine()) != null)
{
     string[] splitString = line.Split(',');
     int.TryParse(splitString[0], out ageGroups[counter]);
     int.TryParse(splitString[3], out districts[counter]);
     counter++;          
}

这将为您提供两个长度为districts的数组ageGroups1024,并将包含census.txt文件中每行的值。

相关问题