在C中,我可以读取输入,并在程序到达文件末尾时停止该程序(EOF
)。像这样。如何阅读文件结尾?
#include <stdio.h>
int main(void) {
int a;
while (scanf("%d", &a) != EOF)
printf("%d\n", a);
return 0;
}
我该如何在Lua中做到这一点?
在C中,我可以读取输入,并在程序到达文件末尾时停止该程序(EOF
)。像这样。如何阅读文件结尾?
#include <stdio.h>
int main(void) {
int a;
while (scanf("%d", &a) != EOF)
printf("%d\n", a);
return 0;
}
我该如何在Lua中做到这一点?
Lua Documentation具有大量关于文件读取和其他IO的细节。用于读取整个文件:
t = io.read("*all")
显然读取整个文件。该文档有逐行阅读的例子等。希望这有助于。上读取文件的所有行和编号他们每个人(线逐线)
实施例:
local count = 1
while true do
local line = io.read()
if line == nil then break end
io.write(string.format("%6d ", count), line, "\n")
count = count + 1
end
您的示例程序没有行编号,但引用了可打印编码。 (它应该更好地处理较低的控制字符,我想。) – 2011-02-23 20:50:38
我的坏人 - 错误的例子被粘贴在:)这两个都在文档中可用:) – 2011-02-23 20:57:48