[英]Input array in Free Basic
現在,我正在使用Free Basic進行編程,並且正在尋找一種方法來在一行中獲取數組的值。
例如,如果我想在一行中獲得一個數組的2個整數,則可以這樣寫:
Dim a(2) as integer
Input a(1),a(2)
但是我的程序應該從用戶那里獲取數組長度。
這是我的程序:
dim length as integer
input "Enter Array length: ",length
dim a(length) as integer
dim i as integer
for i=1 to length
input a(i)
next
'OTHER CODES...
但是該程序會多行獲取Array值。 問題就在這里。 我想將其放在一行中,但是我不知道“我該怎么辦?”
有人可以幫我嗎?
是的 最好的方法可能是獲取整個字符串並自己解析數字。 但是為此,您需要使用line input
而不是input
,因為input
只會在第一個逗號之前返回字符串,而line input
將返回整個字符串。
不幸的是,FreeBasic的弱點是字符串解析,因此您需要使用一個庫或構建自己的函數來解析數字。 這是一個例子:
declare sub explode_to_integers(s as string, a() as integer, delimiter as string=",")
sub explode_to_integers(s as string, a() as integer, delimiter as string = ",")
dim i as integer
dim idx as integer = 0
while len(s)
if idx > ubound(a) then
redim preserve a(idx) as integer
end if
i = instr(s, delimiter)
if i then
a(idx) = cast(integer, left(s, i-1))
s = right(s, len(s)-i)
else
a(idx) = cast(integer, s)
s = ""
end if
idx += 1
wend
end sub
您將像這樣使用它:
dim numbers as string
redim a() as integer
line input "Enter numbers: ", numbers
explode_to_integers(numbers, a()) '// split string by comma and put values into a()
dim i as integer
for i = 0 to ubound(a)
print a(i)
next i
end
確保在聲明數組時使用redim
,以便可以在運行時調整數組的大小。
如果您輸入的是所有數字(不帶逗號)和/或文本不帶引號,那么這很簡單:
Dim as integer x,x1,y,y1
Dim as string string1,string2
print "Be sure to use commas between values, if you need a comma in a string,"
print "use double quotes around the string."
Input "Enter x,x1,string1,y,y1,string2", x,x1,string1,y,y1,string2
如果您需要讀取大多數CSV文件,則相同的技術非常有效。
Input #filehandle, x,x1,string1,y,y1,string2
請注意,這不會處理字符串中的嵌入式引號,它將在第二個雙引號處而不是在下一個未引號逗號處截斷字符串。
換句話說,如果您: input #1, string1,x
並且文件包含
"hello"world", 2
您只會打招呼和2。 (從FB v 1.01開始),我認為這是一個錯誤,因為您可以在其他地方使用帶嵌入式引號的字符串。
順便說一句,編寫CSV文件很容易:
Write #filehandle, x,x1,string1,y,y2,string2
希望這會有所幫助,我在其他一些地方也看到了相同的問題。
您必須輸入“字符串”,然后將字符串拆分為給定值的數量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.