私はカレブDoxseyの囲碁本を働いていると私はプログラムが第二scanfの後に停止し、ユーザーの入力を待ちませんなぜ私が疑問に思ってfmt.Scanf
http://www.golang-book.com/4Goのfmt.Scanfがユーザー入力を待たないのはなぜですか?
について2つの質問がありますか?ユーザーが整数を入力したか、空白を残していないかどうかをテストするにはどうすればよいですか?
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))
}
それは私のために正常に動作します。私はそれが行末の問題であると推測するつもりです。 Windows上で走っているならば、行の終わりは通常 '\ r \ n'で表示されますが、Mac OS XとLinuxでは(これをテストしたところで)ただ\ nです。私の推測は、おそらくGoは '\ r'を読んでいて、行の終わりとして扱い、ストリームに '\ n'を残しているということです。 fmt.Scanfをもう一度呼び出すと、すでにバッファに何かがあり、ブロックする必要はありません。しかしこれはただの野生の推測です。 – deong
どのようにそれを修正するための任意の提案?これは私がWindowsのコマンドラインで実行するものです:c:\ Go \ src \ play \ exercise> go loop_exercise.go 平方根を取るために数値を入力してください:2 最初の推測を入力y - > + Inf – Zeynel
あなたが明示的に改行文字をScanf呼び出しで読むと、どうなるでしょうか? "fmt.Scanf("%f \ n "、&inputGuess)' "のように?あるいは、読み込みごとに標準入力をフラッシュすることもできます。私はFlush関数を探す場所を知るのに十分にうまくいくかどうかわかりません。 – deong