duanjue2560 2013-09-24 05:07
浏览 103

Golang-检查参数数量? 同样是用户输入-检查返回键(空白)条目“”

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.Args[1] 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.Args[1] 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条回答 默认 最新

  • douchensou6969 2013-09-24 05:14
    关注
    1. 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 the flag package.

    2. fmt.Scanf returns the number of scanned items so check this. If it's 0, set the answer to an empty string.

    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)