fmt.Scan 如何让程序自动输入?

1. 运行环境

go1.17.6 windows/amd64

2. 问题描述?

程序在运行过程中需要交互,程序中使用了fmt.scan(),
交互方式有两种,一种是通过键盘输入,一种是程序自动读取某文件。
现在无法实现程序自动输入后继续执行。
麻烦大家这个自动输入如何实现。

3. 您期望得到的结果?

4. 您实际得到的结果?

讨论数量: 1
pardon110

流操作,只不过前者基于系统标准输入流,后者是改用文件流。若是要命令行交互,使用 cobra 库更为合适。

// Scan scans text read from standard input, storing successive
// space-separated values into successive arguments. Newlines count
// as space. It returns the number of items successfully scanned.
// If that is less than the number of arguments, err will report why.
func Scan(a ...any) (n int, err error) {
    return Fscan(os.Stdin, a...)
}

Go

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!