I am working through Caleb Doxsey's Go book and I have two questions about fmt.Scanf http://www.golang-book.com/4
I am wondering why the program does not stop after the second Scanf and wait for user input? And how do I test if the user entered an integer and/or did not leave blank?
package main import ( "fmt" //"math" ) // compute square roots by using Newton's method func main() { var x float64 //number to take square root var y float64 //this is the guess var q float64 //this is the quotient var a float64 //this is the average // how do check if the user entered a number fmt.Print("Enter a number to take its square root: ") var inputSquare float64 fmt.Scanf("%f", &inputSquare) // why doesn't program stop after // the Print statement and wait // for user input? fmt.Print("Enter first guess ") var inputGuess float64 fmt.Scanf("%f", &inputGuess) //x = 2 x = inputSquare y = inputGuess for i := 0; i < 10; i++ { //set up the for loop for iterations q = x/y //compute the quotient; x and y are given a = (q + y) / x //compute the average y = a //set the guess to the average } //for the next loop fmt.Println("y --> ", y) //fmt.Println("Sqrt(2)", math.Sqrt(2)) }
fmt.Scanf("%f\n", &inputGuess)"? Alternately, you could flush stdin after each read. I don't know go well enough to know where to tell you to look for a Flush function.\nfixed the issue.