新手问题:要求用户在终端中输入一个有效的目录,以便输入到Go程序中。

huangapple go评论70阅读模式
英文:

Rookie Question: Require user to enter a valid directory in the terminal for input into Go program

问题

新手问题:我正在尝试编写一个程序,该程序接受从终端输入的目录,并在程序中对该目录执行后续操作。如果用户没有输入存在的目录,我该如何让程序继续要求用户输入有效的目录?我在这个程序上遇到的错误在底部列出。我最初尝试使用fmt.Scan()来获取用户输入,现在转向bufio扫描器,但是我不知道该怎么做,所以想请教专家。非常感谢任何帮助!

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	fmt.Println("What file path would you like to search?")
	
	input := bufio.NewScanner(os.Stdin)

	for input.Scan() {
		text := input.Text()
		x, _ := os.Stat(text)
		if x.IsDir() {
			fmt.Println("Cool this is a directory")
		} else {
			fmt.Println("Sorry, this is not a directory")
			continue
		}
	}
}

错误:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x48b465]

英文:

Rookie Question: I'm trying to write a program that takes a directory that is entered into the terminal to perform a later action in the program on that directory. If the user does not enter a directory that exists, how do I get the program to keep asking the user to enter in a valid directory? The error I'm getting on this program is listed at the bottom. I originally tried the fmt.Scan() to get the user input, have now moved onto the bufio scanner, and am at a loss so figured I would ask the experts. Much thanks for any help!

package main

import (
"bufio"
"fmt"
"os"
)

	
fmt.Println("What file path would you like to search?")
	
input := bufio.NewScanner(os.Stdin)

	for input.Scan() {
		text := input.Text()
		x, _ := os.Stat(text)
		if x.IsDir() {
			fmt.Println("Cool this is a directory")
		} else {
			fmt.Println("Sorry, this is not a directory")
			continue

		}

	}
}```

Error:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x48b465]

</details>


# 答案1
**得分**: 2

你可以在os.Stat()函数中捕获错误。代码片段应该类似于这样:

```go
        x, err := os.Stat(text)
		if err != nil {
	        fmt.Println("重新输入有效的目录:")
			continue
		}
英文:

You could capture the error on the os.Stat() function. The code snippet would look something like this

        x, err := os.Stat(text)
		if err != nil {
	        fmt.Println(&quot;Re-enter a valid dir:&quot;)
			continue
		}

答案2

得分: 1

你可能想要检查Scan方法的输出以及可能发生的任何错误。

根据文档

Scan方法将Scanner推进到下一个标记,然后可以通过Bytes或Text方法访问该标记。当扫描停止时(无论是到达输入的末尾还是发生错误),它将返回false。在Scan返回false之后,Err方法将返回扫描过程中发生的任何错误,但如果是io.EOF,则Err将返回nil。如果分割函数返回太多的空标记而不推进输入,则Scan会引发panic。这是扫描器的常见错误模式。

因此,尝试检查Err()方法是否有错误,并检查input.Scan调用的返回值。

英文:

You might want to check the output of the Scan method, and any errors that might have happened there.

According to the documentation:

> Scan advances the Scanner to the next token, which will then be
> available through the Bytes or Text method. It returns false when the
> scan stops, either by reaching the end of the input or an error.
> After Scan returns false, the Err method will return any error that
> occurred during scanning, except that if it was io.EOF, Err will
> return nil. Scan panics if the split function returns too many empty
> tokens without advancing the input. This is a common error mode for
> scanners.

So, try checking out the Err() method for any errors and checking the input.Scan call's return value.

huangapple
  • 本文由 发表于 2021年11月3日 11:20:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/69819297.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定