c#如何存储数组中文件的值[重复]

时间:2023-02-09 13:32:47

This question is an exact duplicate of:

这个问题与以下内容完全相同:

I am trying to store values in an array from reading from a file. I have the reading from a file part but I can't get it to store in an array because it gives me an error "Value cannot be null" because after the loop the value of my variable becomes null and the array cannot be null. Here's what I have. And I realize that the for loop probably isn't in the correct spot so any help with where to put it would be great.

我试图通过从文件中读取来存储数组中的值。我有一个文件部分阅读,但我不能让它在阵列存储,因为它给了我一个错误“值不能为空”,因为在循环后我的变量的值变为零和数组不能为空。这就是我所拥有的。而且我意识到for循环可能不在正确的位置,所以任何帮助放在哪里都会很棒。

    Program p = new Program();

        int MAX = 50;

        int[] grades = new int[MAX];

        string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";

        string path = environment + "grades.txt";

    StreamReader myFile = new StreamReader(path);

        string input;

        int count = 0;

        do
        {
            input = myFile.ReadLine();
            if (input != null)
            {
                WriteLine(input);
                count++;
            }
        } while (input != null);

        for (int i = 0; i < count; i++)
        {
            grades[i] = int.Parse(input);
        }

4 个解决方案

#1


1  

You start the for loop just after exiting from the while loop. And the condition to exit from the while loop is true when input is null. Of course this is not well accepted by Int.Parse.
Instead you can use a single loop, taking in consideration that you don't want to loop more than 50 times otherwise you exceed the array dimensions

刚从while循环退出后启动for循环。当输入为空时,退出while循环的条件为true。当然,Int.Parse并没有很好地接受这一点。相反,你可以使用一个循环,考虑到你不想循环超过50次,否则你超过了数组维度

int count = 0;
while((input = myFile.ReadLine()) != null && count < 50)
{
    WriteLine(input);
    grades[count] = int.Parse(input);
    count++;
}

However you can have a more flexible way to handle your input if you use a List<int> instead of an array of integers. In this way you don't have to check for the number of lines present in your file

但是,如果使用List 而不是整数数组,则可以使用更灵活的方式来处理输入。这样您就不必检查文件中存在的行数

List<int> grades = new List<int>();
while((input = myFile.ReadLine()) != null)
    grades.Add(int.Parse(input));

#2


1  

if we want to get really condensed

如果我们想要真正凝聚

var grades = File.ReadAllLines(path).Select(l=>Int.Parse(l)).ToArray();

#3


0  

Utilize the Path.Combine() to help you in concatenating paths.

利用Path.Combine()来帮助您连接路径。

    string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
    String fullPath = Path.Combine(environment, "grades.txt");

    int[] grades = File.ReadAllLines(fullPath).Select(p => int.Parse(p)).ToArray<int>();
    Console.WriteLine(grades);

c#如何存储数组中文件的值[重复]

Refer to https://www.dotnetperls.com/file-readalllines on how to use File.ReadAllLines() its very handy.

有关如何使用File.ReadAllLines()的信息,请参阅https://www.dotnetperls.com/file-readalllines非常方便。

I'm using LINQ here, which sometimes simplifies things. Even though it looks a bit intimidating now. We read all lines, the result of that is then parsed by selecting each one and converting it to an integer then outputting an array of integers and saving that to grades.

我在这里使用LINQ,这有时简化了事情。即使它现在看起来有点吓人。我们读取所有行,然后通过选择每个行并将其转换为整数然后输出整数数组并将其保存到成绩来解析结果。

#4


0  

Program p = new Program();
int MAX = 50;
int[] grades = new int[MAX];
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
string path = environment + "grades.txt";
using (StreamReader myFile = new StreamReader(path))
{
    string input;
    int count = 0;
    while((!myFile.EndOfStream) && (count < MAX))
    {
        input = myFile.ReadLine();
        if (!String.IsNullOrWhiteSpace(input))
        {
            WriteLine(input);
            grades[count] = int.Parse(input);
            count++;
        }
    }
}

You should definitely use the "using" pattern around your stream object. Got rid of the for-loop for you while maintaining mostly your code and style. Your issue was that you weren't using the input value before moving on to the next line. You only ever had the last value in your original code.

你绝对应该使用流对象周围的“使用”模式。摆脱for循环,同时保持你的代码和风格。您的问题是您在转到下一行之前没有使用输入值。您只有原始代码中的最后一个值。

#1


1  

You start the for loop just after exiting from the while loop. And the condition to exit from the while loop is true when input is null. Of course this is not well accepted by Int.Parse.
Instead you can use a single loop, taking in consideration that you don't want to loop more than 50 times otherwise you exceed the array dimensions

刚从while循环退出后启动for循环。当输入为空时,退出while循环的条件为true。当然,Int.Parse并没有很好地接受这一点。相反,你可以使用一个循环,考虑到你不想循环超过50次,否则你超过了数组维度

int count = 0;
while((input = myFile.ReadLine()) != null && count < 50)
{
    WriteLine(input);
    grades[count] = int.Parse(input);
    count++;
}

However you can have a more flexible way to handle your input if you use a List<int> instead of an array of integers. In this way you don't have to check for the number of lines present in your file

但是,如果使用List 而不是整数数组,则可以使用更灵活的方式来处理输入。这样您就不必检查文件中存在的行数

List<int> grades = new List<int>();
while((input = myFile.ReadLine()) != null)
    grades.Add(int.Parse(input));

#2


1  

if we want to get really condensed

如果我们想要真正凝聚

var grades = File.ReadAllLines(path).Select(l=>Int.Parse(l)).ToArray();

#3


0  

Utilize the Path.Combine() to help you in concatenating paths.

利用Path.Combine()来帮助您连接路径。

    string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
    String fullPath = Path.Combine(environment, "grades.txt");

    int[] grades = File.ReadAllLines(fullPath).Select(p => int.Parse(p)).ToArray<int>();
    Console.WriteLine(grades);

c#如何存储数组中文件的值[重复]

Refer to https://www.dotnetperls.com/file-readalllines on how to use File.ReadAllLines() its very handy.

有关如何使用File.ReadAllLines()的信息,请参阅https://www.dotnetperls.com/file-readalllines非常方便。

I'm using LINQ here, which sometimes simplifies things. Even though it looks a bit intimidating now. We read all lines, the result of that is then parsed by selecting each one and converting it to an integer then outputting an array of integers and saving that to grades.

我在这里使用LINQ,这有时简化了事情。即使它现在看起来有点吓人。我们读取所有行,然后通过选择每个行并将其转换为整数然后输出整数数组并将其保存到成绩来解析结果。

#4


0  

Program p = new Program();
int MAX = 50;
int[] grades = new int[MAX];
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
string path = environment + "grades.txt";
using (StreamReader myFile = new StreamReader(path))
{
    string input;
    int count = 0;
    while((!myFile.EndOfStream) && (count < MAX))
    {
        input = myFile.ReadLine();
        if (!String.IsNullOrWhiteSpace(input))
        {
            WriteLine(input);
            grades[count] = int.Parse(input);
            count++;
        }
    }
}

You should definitely use the "using" pattern around your stream object. Got rid of the for-loop for you while maintaining mostly your code and style. Your issue was that you weren't using the input value before moving on to the next line. You only ever had the last value in your original code.

你绝对应该使用流对象周围的“使用”模式。摆脱for循环,同时保持你的代码和风格。您的问题是您在转到下一行之前没有使用输入值。您只有原始代码中的最后一个值。