I'm trying to read in a file consisting of lines of text of the following sort of form...
first value 1352.2 second value 12 third value 32323
first value 1233.2 second value 22 third value 23333
first value 1233.1 second value 21 third value 64344
so I'm looking for a function analagous to fscanf or sscanf to munch each line up in one go. Is there such a function or must I pick apart each line by hand (there are several different kinds of lines).
There's no equivalent of
sscanf
. I would just pick the lines apart by hand using Mid(). It's fairly easy.Mid(string, start, length)
will return a substring, starting at characterstart
, andlength
characters long.start
is 1-based - the first character in the string is number 1.start
andlength
. What will the file look like if it contains a really large number? Probably the number will extend further to the left (if the numbers are right-aligned in the file, which is common in my experience - your mileage may vary).Val
to convert the substrings to numbersPersonally I would avoid Input #.
Input #
is intended for reading files written from VB6 usingWrite #
. If you try to read an arbitrary file format withInput #
, you might encounter odd edge cases.While MarkJ has given you the VB6 way of doing things, you may want to check out FWIW:
http://www.freevbcode.com/ShowCode.asp?ID=3806
"C String Functions SScanf and StrTok Implemented in VB"
It implements a function ScanString() that's supposed to be an emulation of sscanf().
The Input statement should be sufficient for most cases (maybe with some logic to detect the type of line and call the relevant input statement).
There is a fairly comprehensive examination of different file IO commands in VB6 with some nice examples of reading a 'COBOL-style' fixed with file over here.
If you are dealing with an odd or inconsistent format that Input can't deal with, as you say it is possible to pick apart by hand. This might be the best option as you mention there are different formats.
Given a file like that, you can use whatever method you like to read the file line by line, then use the
Trim
andSplit
functions to create a string array of space-delimited strings for each line. Then parse the numbers from the resulting array by keeping those elements that returnTrue
from theIsNumeric
function:Put this in the immediate window to see how this would work:
When you press enter after
Next x
, you'll see this, where every number is followed by a "True":Note: I put the leading double quote on each print line so that the syntax highlighting wouldn't mess with the output.