问题
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