VB编程如何将*.txt文件中的数据读入到数组

yarui0301 2008-03-09 03:47:45
比如说有一个文件temp.txt,内容是:
speed=12
gx=4
gy=7
gz=3
xx=1
yy=2
zz=3

等上千个数,如何用VB编程将这些数据读入到一个数组a()中?

注意:是只读数据,要过滤掉前面的字符

恳请高手相助,感激不尽!!
...全文
1731 14 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
yarui0301 2008-03-14
  • 打赏
  • 举报
回复
哈哈,谢谢啊,问题解决了,用vbman2003方法试了试,问题解决了,非常感谢哦
嘻嘻
lyserver 2008-03-14
  • 打赏
  • 举报
回复
如果是以回车换行符为间隔符的话,其实还有更好的办法,首先一次性读入全部文件内容,然后使用split函数,该函数返回值即为一个数组.
xiao_xiong0520 2008-03-12
  • 打赏
  • 举报
回复
我刚学,还是个新手,试着做了一下,希望大家指点指点
Option Explicit
Dim a$, n%, k%, c$(), d%

Private Sub Form_Click()
n = 0
Open App.Path & "\temp.txt" For Input As #1
Do Until EOF(1)
n = n + 1
Line Input #1, a
ReDim c(n)
d = Len(a)
k = InStr(1, a, "=")
c(n) = Right(a, (d - k + 1))
Print "c(" & n & ")=" & c(n)
Loop
Close #1
End Sub
嗷嗷叫的老马 2008-03-09
  • 打赏
  • 举报
回复
路过.......
bluefox1979 2008-03-09
  • 打赏
  • 举报
回复
用FSO操作文本文件
sonic_andy 2008-03-09
  • 打赏
  • 举报
回复
加到字典好操作:

dim dict as dictionary
dim fso as filesystemobject

dim stream as textstream
set stream = fso.opentextfile("c:\temp.txt",forreading)

dim content as string
content = stream.readall()

dim arr() as string
arr = split(content,vbcrlf)

dim i as long
for i=lbound(arr) to ubound(arr)
dim temp() as string
temp = split(arr(i),"=")
call dict.add(temp(0),temp(1))
next
qiu5208 2008-03-09
  • 打赏
  • 举报
回复
把所有文件中的所有内容读到一个字串,
然后用上面的方法。
cbm6666 2008-03-09
  • 打赏
  • 举报
回复
Dim aa$, s, ss
Private Sub Form_Load()
Open "c:\temp.txt" For Input As #1
aa = StrConv(InputB(LOF(1), 1), vbUnicode)
Close #1
End Sub

Private Sub Command1_Click()
s = Split(aa, vbNewLine)
For i = 0 To UBound(s)
If s(i) <> "" Then
ss = Split(s(i), "=")
Print Val(ss(1))
End If
Next i
End Sub

vbman2003 2008-03-09
  • 打赏
  • 举报
回复
哦,实际上上面的代码只是个示例,是一个思路,没测试。可能会有点问题,因为文本格式不同,或者文本最后有空格等等,所以数组a可能会出现空值。最好用trim(a(i))<>"" 判断后,赋值给一个新的数组
vbman2003 2008-03-09
  • 打赏
  • 举报
回复
上面代码的前题是=号右边是数字
vbman2003 2008-03-09
  • 打赏
  • 举报
回复


dim s as string
dim h as long

'将文本内容读入变量s
h=freefile
open "c:\temp.txt" for binary as h
s=space(lof(h))
get h,,s
close

'然后可以按上面yarui0301的方法处理
'不过最好加个判断
dim i as long
dim a() as string

a=split(s,"=")
for i=0 to ubound(a)
if trim(a(i))<>"" then a(i)=val(a(i))
next

zdingyun 2008-03-09
  • 打赏
  • 举报
回复
你用记事本打开temp.txt文件是何种结构?才能决定如何读取文件并将数据放入数组.
temp.txt文件可能如下:
speed=12
gx=4
gy=7
gz=3
xx=1
yy=2
zz=3
....

temp.txt文件也可能如下:
speed=12 gx=4 gy=7 gz=3 xx=1 yy=2 zz=3
....

temp.txt文件也可能如下:
speed=12,gx=4,gy=7,gz=3,xx=1,yy=2,zz=3
....
yarui0301 2008-03-09
  • 打赏
  • 举报
回复
非常感谢
但是我的这个文件里面有上千个(大概5000个)这样的数值,这样一个一个写是不现实的,那该怎么办呢?
qiu5208 2008-03-09
  • 打赏
  • 举报
回复
Private Sub Command1_Click()
Dim a As String
a = "speed = 12 gx = 4 gy = 7 gz = 3 xx = 1 yy = 2 zz = 3"
Dim b() As String

b = Split(a, "=")
Dim i As Integer
For i = 0 To UBound(b)
b(i) = Val(b(i))
Print b(i)
Next

End Sub

7,785

社区成员

发帖
与我相关
我的任务
社区描述
VB 基础类
社区管理员
  • VB基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧