从文件读取后的命令行输入
Command line input after reading from a file
你好,我正在尝试读取一个包含单词列表的文件,然后让用户在命令行中输入一个数字来选择他的单词。但是,当我 运行 我的代码时,它不允许我输入数字。这是我的代码:
function readFile(file)
array = {}
io.input(file)
line = io.read()
table.insert(array, line)
while true do
line = io.read()
if line == nil then break end
table.insert(array, line)
end
length = #array
count = 1
while count <= length do
print(count .. ". " .. array[count])
count = count + 1
end
return array
end
function chooseWord(wordArr)
local answer
io.write("Select a Number to choose a word")
answer = io.read()
local word = wordArr[answer]
print(word)
return word
end
words = readFile("dictionary.txt")
word = chooseWord(words)
如果我删除 readFile 函数,我可以完美地输入,但是一旦我读取文件,我就是
更好用:
local f = io.open(file, "r")
line = f:read()
f:close()
等等
在您的情况下,您将标准输入文件(使用 io.input)从 stdin 更改为您的文件,之后您必须重新设置它。但这不是一个好的解决方案
你好,我正在尝试读取一个包含单词列表的文件,然后让用户在命令行中输入一个数字来选择他的单词。但是,当我 运行 我的代码时,它不允许我输入数字。这是我的代码:
function readFile(file)
array = {}
io.input(file)
line = io.read()
table.insert(array, line)
while true do
line = io.read()
if line == nil then break end
table.insert(array, line)
end
length = #array
count = 1
while count <= length do
print(count .. ". " .. array[count])
count = count + 1
end
return array
end
function chooseWord(wordArr)
local answer
io.write("Select a Number to choose a word")
answer = io.read()
local word = wordArr[answer]
print(word)
return word
end
words = readFile("dictionary.txt")
word = chooseWord(words)
如果我删除 readFile 函数,我可以完美地输入,但是一旦我读取文件,我就是
更好用:
local f = io.open(file, "r")
line = f:read()
f:close()
等等
在您的情况下,您将标准输入文件(使用 io.input)从 stdin 更改为您的文件,之后您必须重新设置它。但这不是一个好的解决方案