Golang - Check number of arguments? Also User Input - Check for return key (blank line) entry ""

user1945077 picture user1945077 · Sep 24, 2013 · Viewed 19.5k times · Source

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.

Answer

laurent picture laurent · Sep 24, 2013
  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.