英文:
How to add pause to a Go program?
问题
当我执行一个Go控制台程序时,它只会在一秒钟内执行完毕,我已经在Google、Go官网和Stackoverflow上搜索过了。
import (
"fmt"
)
func main() {
fmt.Println()
}
当我执行它时,它立即关闭。
编辑2
实际上,我希望程序能够永久暂停,直到用户按下一个按钮。
英文:
When i ever execute a Go Console program it just executes in one second, I've been looking on Google, the Go website and Stackoverflow.
import (
"fmt"
)
func main() {
fmt.Println()
}
It closes immediately when i execute it.
EDIT 2
actually i wanted the program to permanently stay paused untill the user presses a button
答案1
得分: 87
你可以使用time.Sleep()
来暂停程序任意长的时间。例如:
package main
import ("fmt"
"time"
)
func main() {
fmt.Println("Hello world!")
duration := time.Second
time.Sleep(duration)
}
要任意增加暂停的时间,可以这样做:
duration := time.Duration(10)*time.Second // 暂停10秒
编辑:由于问题的提问者增加了额外的限制,上面的答案不再适用。你可以通过创建一个新的缓冲读取器来暂停,直到按下<kbd>Enter</kbd>键为止,该读取器等待读取换行符(\n
)字符。
package main
import ("fmt"
"bufio"
"os"
)
func main() {
fmt.Println("Hello world!")
fmt.Print("按下'Enter'键继续...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
英文:
You can pause the program for an arbitrarily long time by using time.Sleep()
. For example:
package main
import ( "fmt"
"time"
)
func main() {
fmt.Println("Hello world!")
duration := time.Second
time.Sleep(duration)
}
To increase the duration arbitrarily you can do:
duration := time.Duration(10)*time.Second // Pause for 10 seconds
EDIT: Since the OP added additional constraints to the question the answer above no longer fits the bill. You can pause until the <kbd>Enter</kbd> key is pressed by creating a new buffer reader which waits to read the newline (\n
) character.
package main
import ( "fmt"
"bufio"
"os"
)
func main() {
fmt.Println("Hello world!")
fmt.Print("Press 'Enter' to continue...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
答案2
得分: 26
package main
import "fmt"
func main() {
fmt.Println("按下回车键以终止控制台屏幕!")
fmt.Scanln() // 等待回车键
}
英文:
package main
import "fmt"
func main() {
fmt.Println("Press the Enter Key to terminate the console screen!")
fmt.Scanln() // wait for Enter Key
}
答案3
得分: 15
最简单的另一种方法是使用最少的导入,使用以下两行代码:
var input string
fmt.Scanln(&input)
在程序的末尾添加这行代码,将暂停屏幕,直到用户按下回车键,例如:
package main
import "fmt"
func main() {
fmt.Println("按下回车键以终止控制台屏幕!")
var input string
fmt.Scanln(&input)
}
英文:
The easiest another way with minimal imports use this 2 lines :
var input string
fmt.Scanln(&input)
Adding this line at the end of the program, will pause the screen until user press the Enter Key, for example:
package main
import "fmt"
func main() {
fmt.Println("Press the Enter Key to terminate the console screen!")
var input string
fmt.Scanln(&input)
}
答案4
得分: 0
我只使用了一行代码fmt.Scanln
。
英文:
import "fmt"
func main() {
fmt.Scanln()
}
I use fmt.Scanln
just one line.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论