C# StreamReader input files from labels?

醉酒当歌 提交于 2019-12-02 03:47:38

问题


I have been using a StreamReader inputFile code from a ListBox and it works great, However, I would like to input the data from the .txt file into a Label box instead, is this possible? This is the code I tried and it gives me an error description stating

Use of unassigned local variable 'total'

 

private void Form1_Load(object sender, EventArgs e)
{
  try
  {
      int total = 0; 
      int highScore;
      StreamReader inputFile;
      inputFile = File.OpenText("HighScore.txt");
      while (!inputFile.EndOfStream)
      {
          highScore = int.Parse(inputFile.ReadLine());
          total += highScore;
      }
      inputFile.Close();
      highscoreLabel.Text = total.ToString("c");
  }
  catch (Exception ex)
  {
      MessageBox.Show(ex.Message);
  }
}

回答1:


The message you are seeing ("Use of unassigned local variable 'total'") relates to "definite assignment", which would be the scenario:

int total; // note not yet assigned a value

...

total += {whatever}

However, in the code you post, it is definitely assigned (initialized to zero). Therefore, I suspect that either the error message has been mis-copied, or the code sample is not a direct copy of the failing case.




回答2:


The error is not in the code!
It is in the format of the text file! If there are any characters other than integers, the code will generate this error - " Input string was not in correct format" (I guess by int.Parse() method!)



来源:https://stackoverflow.com/questions/13172171/c-sharp-streamreader-input-files-from-labels

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!