odd ReadLine quirk

Blitz3D Forums/Blitz3D Programming/odd ReadLine quirk

_PJ_(Posted 2003) [#1]
I thought I should mention this here, in case it helps anyone else, and also because I'm not sure it warrants going in the Bug Reports (it may be just my bad programming habits)
---------------------

Here is an example of what I had:



DataFile=OpenFile("Filename.txt")
Initial_Value=10
New_Value=(Initial_Value+(ReadLine(DataFile))
CloseFile(DataFile)


Which gave really large numbers, completely inaccurate results. I thought it may be adding the memory reference of the 'DataFile' handle, but it didn't even seem to tally with that.

I solved it, very simply by adding another line with a temporary value:

DataFile=OpenFile("Filename.txt")
Initial_Value=10
Temporary=ReadLine(DataFile)
CloseFile(DataFile)
New_Value=Initial_Value+Temporary



Koriolis(Posted 2003) [#2]
Indeed, this is not a bug :)

ReadLine returns a string, not an integer, so doing
Initial_Value+(ReadLine(DataFile)
will convert Initial_Value to a string, then concat it to the line read in the file (an integer, in the form of a string), and then convert this string into an integer just before assigning it to New_Value.
Thus, if your line (in the file) contains "123", what it does is this:
Int(10+"123") = Int("10"+"123") = Int("10123") = 10123
Which is clearly not what you want.
Normally if you do
New_Value=(Initial_Value+Int(ReadLine(DataFile))
that should work without any problem.
Your second version also works because the temporary variable is also an integer, thus it forces the string to int conversion.


_PJ_(Posted 2003) [#3]

Int(10+"123") = Int("10"+"123") = Int("10123") = 10123


Ah of course!

I actually had a similar problem a while back, so I should have known!

Thanks for the explanation, Koriolis!