我已经为此寻找了相当长的时间。有谁知道如何在 Fortran 语言的控制台应用程序中清除屏幕?任何帮助都会非常感激!
7 回答
Fortran, qua Fortran, knows nothing of such concepts as screens or keyboards or, for that matter, computers. There is, therefore, no language-standard way of clearing a screen from Fortran. You will have to find some platform-dependent approach.
Most Fortran compilers have some way of doing this, for example Intel Fortran provides the SYSTEM function.
与其他人相反,我不会调用SYSTEM()
(标准 Fortran 2008 替代方案是execute_command_line()
),但我会打印正确的 ANSI 转义码http://en.wikipedia.org/wiki/ANSI_escape_code:
print *, achar(27)//"[2J"
这将比调用快得多SYSTEM()
。
这适用于典型的 Linux 终端,但不适用于 MS Windows 终端。
如何使用转义码的另一个更实用的参考是http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html
在 Fortran 90/95 中,您最好的选择是系统命令,它是供应商提供的扩展(即,不是 F90/95 标准的一部分,因此一些晦涩的 Fortran 编译器可能没有它,但所有主要编译器都有)。
$ cat clear.f90
program
call system('clear')
end
$ gfortran clear.f90 -o clear
$ ./clear
It depends on your specific sytem and compiler. There is no general way. Fortran doesn't know about specific hardware devices like terminal screens and printers. (Neither do most other languages). The details depend entirely on your specific system.
My advice would be to clear the terminal by invoking the relevent script via the command line - but this is not nice. it is generally more portable to write the output to an ordinary text file and then execute appropriate system commands to print that file to screen. This way you can manipulate the file as you wish...
See here for a simalar question from which these some of the above text was salvaged.
在 FortranACHAR(N)
中返回 N 的 ASCII,所以我首选的方法是:
WRITE(*,'(2f15.9,A5)',advance='no') float1,float2,ACHAR(13)
ACHAR(13)
\r
在 Python 中返回回车符。所以打印后,它会将光标返回到可以被覆盖的行的开头。
退出循环后,您可以使用它CALL SYSTEM('clear')
来清洁屏幕。
这很有帮助,因为CALL SYSTEM('clear')
速度较慢且占用大量 CPU,您可以通过将上述方法替换为
WRITE(*,'(2f15.9)',advance='no') float1,float2;CALL SYSTEM('clear')
并检查循环所用时间的差异。
这在 FTN95 中对我有用
program
call system('CLS')
end
我找到了另一种在类 UNIX 系统中通过打印clear
命令输出来清除屏幕的方法
(来自 clear 命令的手册,其中指出您可以将输出写入文件然后cat
清除屏幕)
所以更好的方法是clear > temp.txt
在打印语句中使用文件中的字符
尽管两者都做同样的事情,但调用 SYSTEM("foo") 比直接打印这些字符慢得多(100 倍以上)
例如:
program clear
implicit none
INTEGER::i
do i = 1, 1000
print *, "Test"
call system("clear")
enddo
end program clear
这个程序需要3.1 到 3.4秒之间的任何时间。
但是如果我直接打印这样的字符,而不是调用系统:
program clear
implicit none
INTEGER::i
do i = 1, 1000
print *, "Test"
print *, "[H[2J[3J"
enddo
end program clear
这会产生完全相同的结果,但需要0.008 到 0.012秒(8 到 12 毫秒)之间的任何时间
实际上,运行第二个循环 100,000 比CALL SYSTEM("clear")
1000 倍快
编辑:不要从这里复制粘贴,它不起作用,(字符在 StackOverflow 上被替换)
只需使用clear > file
并将文件的内容复制到打印语句中