Short Answer:
Use either
int.Parse();
Convert.ToInt32();
methods like this :
int[] arrayData = new int[12];
StreamReader scores = new StreamReader("scores.txt")
while (scores.Peek() != null)
{
arrayData[counter] = int.Parse(scores.ReadLine());
counter = counter + 1;
}
scores.Close();
You need to convert the string value to int so that you can assign it or use it in comparisons such as
if (x > y) …
Long Explanation:
The error is self explanatory, You are reading an string and are trying to assign it to a whole different type!
The ReadLine() method returns a string, And string is different than int.
In C#
you have different types and for each of them you must use a compatible value.
int
is number (actually a number is an integer so you use int to store and work with numbers ( integer values).
string is an array of characters such as
"Ali","Alex","Apple",....
anything which is placed between a double quote is considered a string in c#.
so basically
1 doesn't equal to "1"
Although they look the same, they are completely different.(its as if you compare a picture of an apple with a real one! they look the same, but they are completely two different things!)
So if you need to extract that number out of the string, you need conversion and in that case if you want to have a conversion you can use Convert.ToInt()
method
you may also use :
Int32.Parse();
Have a look at here
And Also a similar question here
For the same reason you can not use such operators on different types.
So to cut a long story short,
you need to do this :
int[] arrayData = new int[12];
StreamReader scores = new StreamReader("scores.txt")
while (scores.Peek() != null)
{
arrayData[counter] = int.Parse(scores.ReadLine());
counter = counter + 1;
}
scores.Close();