How do I use the fmt.Scanf
function in Go to get an integer input from the standard input?
If this can't be done using fmt.Scanf
, what's the best way to read a single integer?
To read an integer with scanf, use %d . Mixing scanf and get / fgets doesn't work well. Anyway scanf is not at all made for interactive user input. See answer below.
To read integers from console, use Scanner class. Scanner myInput = new Scanner( System.in ); Allow a use to add an integer using the nextInt() method. System.
char c; scanf(" %c", &c); reads the next non-white-space character in the standard input and stores it into variable c. is a typical way to use scanf. Expression eof() is true if an attempt to read the standard input has been done, and the standard input was found to have nothing left in it.
Let's take a look at how we read and write integers. Numbers like eight, negative four, 15, negative 76, and zero are all examples of integers. An integer is any number in this set, where the dot dot dots on either side means continues without end. The word “integer” comes from the Latin word that means “whole.”
http://golang.org/pkg/fmt/#Scanf
All the included libraries in Go are well documented.
That being said, I believe
func main() { var i int _, err := fmt.Scanf("%d", &i) }
does the trick
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With