本文整理汇总了Golang中fmt.Scanln函数的典型用法代码示例。如果您正苦于以下问题:Golang Scanln函数的具体用法?Golang Scanln怎么用?Golang Scanln使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Scanln函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
var x float32
var y int
var ch1, ch2 string
var name string
fmt.Println("Enter a character")
if _, err := fmt.Scanln(&ch1); err != nil {
fmt.Println("Error:", err)
}
fmt.Println("Enter a number")
if _, err := fmt.Scanln(&y); err != nil {
fmt.Println("Error:", err)
}
fmt.Println("Enter another character")
if _, err := fmt.Scanln(&ch2); err != nil {
fmt.Println("Error:", err)
}
fmt.Println("Enter a name")
if _, err := fmt.Scanf("%s", &name); err != nil {
fmt.Println("Error:", err)
}
fmt.Println("Enter a floating point value")
if _, err := fmt.Scanf("%g", &x); err != nil {
fmt.Println("Error:", err)
}
// Display the values read
fmt.Printf("ch1\t=\t%s\ny\t=\t%d\nch2\t=\t%s\nName\t=\t%s\nx\t=\t%g\n",
ch1, y, ch2, name, x)
}
示例2: runLogin
func runLogin(cmd *Command, args []string) {
if len(args) != 0 {
cmd.PrintUsage()
os.Exit(2)
}
oldEmail := client.Username
var email string
if oldEmail == "" {
fmt.Printf("Enter email: ")
} else {
fmt.Printf("Enter email [%s]: ", oldEmail)
}
_, err := fmt.Scanln(&email)
switch {
case err != nil && err.Error() != "unexpected newline":
printFatal(err.Error())
case email == "" && oldEmail == "":
printFatal("email is required.")
case email == "":
email = oldEmail
}
// NOTE: gopass doesn't support multi-byte chars on Windows
password, err := readPassword("Enter password: ")
switch {
case err == nil:
case err.Error() == "unexpected newline":
printFatal("password is required.")
default:
printFatal(err.Error())
}
address, token, err := attemptLogin(email, password, "")
if err != nil {
if herror, ok := err.(heroku.Error); ok && herror.Id == "two_factor" {
// 2FA requested, attempt 2FA login
var twoFactorCode string
fmt.Printf("Enter two-factor auth code: ")
if _, err := fmt.Scanln(&twoFactorCode); err != nil {
printFatal("reading two-factor auth code: " + err.Error())
}
address, token, err = attemptLogin(email, password, twoFactorCode)
must(err)
} else {
must(err)
}
}
nrc, err = hkclient.LoadNetRc()
if err != nil {
printFatal("loading netrc: " + err.Error())
}
err = nrc.SaveCreds(address, email, token)
if err != nil {
printFatal("saving new token: " + err.Error())
}
fmt.Println("Logged in.")
}
示例3: loginAction
func loginAction(c *cli.Context) {
api := getAPI(c)
var url string
var version string
var username string
var password string
fmt.Printf("URL: ")
_, urlErr := fmt.Scanln(&url)
if urlErr != nil {
panic(urlErr)
}
fmt.Printf("Username: ")
_, usernameErr := fmt.Scanln(&username)
if usernameErr != nil {
panic(usernameErr)
}
password, passwordErr := getpass.GetPass()
if passwordErr != nil {
panic(passwordErr)
}
fmt.Printf("Version (default: 1): ")
_, verErr := fmt.Scanln(&version)
if verErr != nil {
version = "1"
}
userData, loginErr := api.Login(url, username, password)
if loginErr != nil {
LogMessage("Error logging in. Please check username/password.", "r")
os.Exit(1)
}
saveConfig(username, userData.ApiKey, url, version, c.GlobalString("config"))
LogMessage("Login successful", "g")
}
示例4: main
func main() {
var pin string
var nickname string
fmt.Print("Enter game pin: ")
fmt.Scanln(&pin)
fmt.Print("Enter nickname: ")
fmt.Scanln(&nickname)
fmt.Println("Connecting...")
conn, err := kahoot.NewConnection(pin)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
if err := conn.Register(nickname); err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Awaiting questions...")
for {
if conn.WaitQuestion() != nil {
fmt.Println("Done question loop:", err)
os.Exit(1)
}
fmt.Print("Got question. Answer: ")
var number string
fmt.Scanln(&number)
parsed, _ := strconv.Atoi(number)
if err := conn.SendAnswer(parsed); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
}
示例5: gravatar
func gravatar() {
var name, email string
fmt.Println("Please enter your first name")
fmt.Scanln(&name)
fmt.Println("Please enter your email")
fmt.Scanln(&email)
email = strings.ToLower(email)
h := md5.New()
io.WriteString(h, email)
finalBytes := h.Sum(nil)
finalString := hex.EncodeToString(finalBytes)
//generate page
t, _ := template.New("tpl3").Parse(`
{{define "Gravatar"}}
<h1>{{.Name}}</h1>
<img src="http://www.gravatar.com/avatar/{{.Email}}"/>
{{end}}
`)
out, _ := os.Create("myGravatar.html")
_ = t.ExecuteTemplate(out, "Gravatar", Person{name, finalString})
}
示例6: main
func main() {
var len1 float64
var bre1 float64
var choice int
fmt.Println("\n********PERIMETER OF SHAPE************\n Enter 1 for Rectangle\n Enter 2 for Circle")
fmt.Scanln(&choice)
switch choice {
case 1:
{
fmt.Println("Enter the length and breadth of rectangle::")
fmt.Scanln(&len1, &bre1)
r := rectangle{len: len1, breadth: bre1}
fmt.Println("Details of the rectangle are:", r)
s := shape(r)
fmt.Println("Perimeter of rectangle is ::", s.perimeter())
}
case 2:
{
var rad float64
fmt.Println("Enter the radius of the Circle")
fmt.Scanln(&rad)
c := circle{radius: rad}
fmt.Println("Details of circle are:", c)
s := shape(c)
s = c
fmt.Println("The perimeter of circle is", s.perimeter())
}
default:
fmt.Println("Wrong Choice")
}
}
示例7: main
func main() {
rows, cols, gen := 0, 0, 0
var row string
var board []string
fmt.Scanf("%d %d", &rows, &cols)
fmt.Scanln(&row)
board = add_wall_row(cols+2, board)
for i := 0; i < rows; i++ {
fmt.Scanln(&row)
row = WALL + row + WALL
board = append(board, row)
}
board = add_wall_row(cols+2, board)
for {
gen += 1
fmt.Printf("Generation %d:\n", gen)
print(board)
new_board := generation(board)
if compare_boards(board, new_board) || gen >= MAX_GENS {
gen += 1
fmt.Printf("Generation %d:\n", gen)
print(new_board)
return
}
board = new_board
}
}
示例8: main
func main() {
n := 0
eps := 1e-2
var a float64
var b float64
fmt.Println("a: ")
fmt.Scanln(&a)
fmt.Println("b: ")
fmt.Scanln(&b)
fmt.Println("n", "a", "b", "m", "|Dx/2|")
for {
m := (a + b) / 2.0
Dx := math.Abs((b - a) / 2.0)
fmt.Println(n+1, a, b, m, Dx)
if f(a)*f(m) < 0 {
b = m
} else {
a = m
}
n++
if Dx < eps {
break
}
}
}
示例9: do_singletest
func do_singletest(wi wordinfo, date time.Time, nr, total int) {
input := ""
question := wi.Word
fmt.Printf("==============================================\n")
fmt.Printf("Question %d/%d:\n", nr, total)
fmt.Printf("\n [[ %s ]]\n", wi.Word)
fmt.Printf("\n\nPress Enter after you remember the meaning of it:\n")
fmt.Printf("\n Reference: %d Test success/fail: %d/%d\n",
wi.Totalfreq, len(wi.Succ_history), len(wi.Fail_history))
fmt.Scanln(&input)
fmt.Printf("----------------------------------------------\n")
fmt.Printf("The maning of %s was:\n%s\n\n",
question, daum_dict(question))
fmt.Printf("----------------------------------------------\n")
fmt.Printf("Were you understanding it well? (Yes/No)\n")
fmt.Scanln(&input)
if strings.HasPrefix(strings.ToUpper(input), "Y") {
wi.Succ_history = append(wi.Succ_history, date)
fmt.Printf("your feedback, Yes applied\n")
} else {
wi.Fail_history = append(wi.Fail_history, date)
fmt.Printf("your feedback, No applied\n")
}
winfos.Wordinfos[wi.Word] = wi
fmt.Printf("----------------------------------------------\n")
fmt.Printf("\n\n\n")
}
示例10: main
func main() {
prime_limit := int(math.Sqrt(float64(sieve_limit)))
l := gen_primes(prime_limit)
if verbose {
log.Println("Generated primes below ", prime_limit)
}
var rows int
fmt.Scanln(&rows)
if verbose {
log.Println(rows, " rows to come.")
}
for i := 1; i <= rows; i++ {
if verbose {
log.Println("Processing line ", i)
}
var start, stop int
fmt.Scanln(&start, &stop)
if verbose {
log.Println("Generating primes between ", start, " and ", stop)
}
r := range_primes(start, stop, l)
if verbose {
log.Println("There are ", len(r), " results.")
}
for _, prime := range r {
fmt.Println(prime)
}
fmt.Println("")
}
}
示例11: main
func main() {
fmt.Println(runtime.NumGoroutine())
//runtime.GOMAXPROCS(1)
//生成随机种子
rand.Seed(time.Now().Unix())
begin := make(chan bool)
go busy(begin)
fmt.Println(runtime.NumGoroutine())
<-begin
fmt.Println("is fucking!")
var input string
fmt.Scanln(&input)
fmt.Println("done1")
var name string
for i := 0; i < 3; i++ {
name = fmt.Sprintf("go_%02d", i) //生成ID
//生成随机等待时间,从0-4秒
go routine(name, time.Duration(rand.Intn(5))*time.Second)
}
fmt.Println(runtime.NumGoroutine())
//让主进程停住,不然主进程退了,goroutine也就退了
fmt.Scanln(&input)
fmt.Println("done")
fmt.Println(runtime.NumGoroutine())
}
示例12: main
func main() {
flag.Parse()
uid := os.Getuid()
euid := os.Geteuid()
if uid != 0 || euid != 0 {
println("grab-box not started with root privileges. Please run grab-box as root.")
return
}
fmt.Println("Welcome to grab-box\n")
if archiveFilename == nil || *archiveFilename == "" {
fmt.Println("What is the username/boxname of the box?")
var slug string
if _, err := fmt.Scanln(&slug); err != nil {
log.Fatal(err)
}
fmt.Println("")
metaUrl := fmt.Sprintf("https://app.wercker.com/api/v2/boxes/%v/*", slug)
response, err := http.Get(metaUrl)
if err != nil {
print("Unable to create response for url: %v", err)
}
defer response.Body.Close()
var metaDoc map[string]interface{}
decoder := json.NewDecoder(response.Body)
if err := decoder.Decode(&metaDoc); err != nil {
print("Unable to decode meta data response: %v", err)
}
boxurl := metaDoc["tarballUrl"].(string)
filename, err := downloadBox(boxurl)
if err != nil {
log.Fatal(err)
}
archiveFilename = &filename
}
if boxName == nil || *boxName == "" {
fmt.Println("What is the name of the box?\n")
if _, err := fmt.Scanln(boxName); err != nil {
log.Fatal(err)
}
}
unpackArchive(*archiveFilename, *boxName)
fmt.Println("\nFixing lxc config...")
fixConfig(fmt.Sprintf("/var/lib/lxc/%v/config", *boxName), *boxName)
fmt.Printf("\n\nFinished! You can execute the following command to start the container:\n\n")
fmt.Printf("\tsudo lxc-start -n '%v'", *boxName)
}
示例13: main
func main() {
var pin string
var nickname string
var answer string
fmt.Print("Game pin: ")
fmt.Scanln(&pin)
fmt.Print("Nickname: ")
fmt.Scanln(&nickname)
fmt.Println("Connecting...")
conn, err := kahoot.NewConnection(pin)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
if err := conn.Register(nickname); err != nil {
fmt.Println(err)
os.Exit(1)
}
for {
fmt.Print("Enter to answer question: ")
fmt.Scanln(&answer)
fmt.Print("Answer: ")
var number string
fmt.Scanln(&number)
parsed, _ := strconv.Atoi(number)
if err := conn.SendAnswer(parsed); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
}
示例14: main
func main() {
guesses := 0
var name string
var guess int
rand.Seed(time.Now().Unix())
randnum := rand.Intn(100)
randnum += 1
fmt.Println("Hello! What is your name?")
fmt.Scanln(&name)
fmt.Printf("Hello %s\n", name)
fmt.Println("I'm thinking of a number between 1 and 100 ")
fmt.Println("What is the number I am thinking of?")
for {
fmt.Scanln(&guess)
guesses++
if guess < randnum {
fmt.Println("Your guess was too low, try again.")
} else if guess > randnum {
fmt.Println("Your guess was too high, try again.")
} else {
fmt.Printf("Congratulations %s! you guessed the number was %d\n", name, randnum)
break
}
}
fmt.Printf("It took you %d guesses to do this\n", guesses)
}
示例15: cmdResetDatabase
func cmdResetDatabase() {
if flagCmdResetDatabase {
if len(flagConfirmBackup) == 0 {
fmt.Print("Have you performed a database backup? (YES/NO): ")
fmt.Scanln(&flagConfirmBackup)
}
if flagConfirmBackup != "YES" {
fmt.Print("ABORTED: You did not answer YES exactly, in all capitals.")
flushLogAndExit(1)
}
var confirm string
fmt.Printf("Are you sure you want to delete everything? ALL data will be permanently deleted? (YES/NO): ")
fmt.Scanln(&confirm)
if confirm != "YES" {
fmt.Print("ABORTED: You did not answer YES exactly, in all capitals.")
flushLogAndExit(1)
}
api.Srv.Store.DropAllTables()
fmt.Print("SUCCESS: Database reset.")
flushLogAndExit(0)
}
}