英文:
Golang - Check number of arguments? Also User Input - Check for return key (blank line) entry ""
问题
两个问题。
- 我正在编写一个小游戏,需要用户在命令行中提供一个参数。命令行输入应该类似于"go run game.go 8"。os.Args[0]是运行的程序(game.go),os.Args1是输入的整数(在这个例子中是8)。我写了以下代码:
s := os.Args[1]
maxLetters, err := strconv.Atoi(s)
if err != nil {
// 处理错误
fmt.Println(err)
os.Exit(2)
}
这段代码将字符串'8'转换为整数,并允许我将其设置为游戏中的最大数。然而,用户有选择不输入数字的选项。在这种情况下,我的程序将默认将最大数设置为7。我的问题是如何在Go中检查os.Args1是否存在。如果存在,将最大数设置为用户输入的数字。如果不存在,将最大数设置为7。
- 在游戏过程中,需要用户输入。"? "标志用于帮助,"(错误的猜测单词)"输入会让他们重试,"(正确的猜测单词)"输入会给他们下一个问题,而只是按下回车键(空行)会退出游戏。我使用以下代码获取他们的输入:
var answer string
fmt.Scanf("%s", &answer)
问题是空行输入(即按下回车键)不被识别。按下回车键不会改变answer的值,因此answer保持不变,游戏继续使用之前的输入作为答案值。显然,这是一个大问题,答案值需要在按下回车键时更改为""或其他值。
有什么建议吗?感谢您的帮助。
英文:
Two questions.
1...I am writing a little game that requires an argument to be provided by the user on the command line. The command line entry would look like "go run game.go 8". os.Args[0] is the program run (game.go), and os.Args1 is the integer entered (in this case 8). I wrote
s := os.Args[1]
maxLetters, err := strconv.Atoi(s)
if err != nil {
// handle error
fmt.Println(err)
os.Exit(2)
}
Which takes the string '8', converts it to an integer, and allows me to set it as a max number in my game. However, they have the option to not enter a number. In this case the max number gets defaulted to 7 in my program. My question is how do I check in golang if os.Args1 exists or not? If it exists, set max to the user's number. If it doesn't exist, set max = 7.
2...During the game, there needs to be user input. "?" flags help, "(incorrect guess word)" entry makes them try again, "(correct guess word)" entry gives them the next question, and simply hitting the return key (a blank line) exits the game. I use
var answer string
fmt.Scanf("%s", &answer)
To obtain their entry. The problem is the "" entry, or blank line entry, is not recognized. Hitting the return key does not change the value of answer, therefore answer stays the same. , and the game proceeds with their previous entry still as the answer value. Obviously this is a big problem and the answer value needs to change to "" or some sort upon hitting the return key.
Any suggestions? Thanks for any help.
答案1
得分: 19
-
由于你只有一个可能的选项,你可以简单地检查
len(os.Args)
- 如果它小于2,就使用默认选项。对于更复杂的情况,可以查看flag
包。 -
fmt.Scanf
返回扫描到的项目数,所以要检查这个值。如果为0,将答案设置为空字符串。
英文:
-
Since you only have one possible option, you can simply check
len(os.Args)
- if it's< 2
, use your default option. For more complex cases, have a look at theflag
package. -
fmt.Scanf
returns the number of scanned items so check this. If it's 0, set the answer to an empty string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论