在Go语言中,可以使用字符串的顺序输出和输入。

huangapple go评论97阅读模式
英文:

Sequential output and input of strings in Go

问题

有一个程序从命令行读取两个输入:用户名和密码。字符串"Password: "应该在输入用户名后才在控制台打印出来,但在我的程序中,它与第一个字符串"Username: "一起立即打印出来。如何修复这个问题?

package main

import (
	"bufio"
	"os"
	"fmt"
)

// 一个简单的程序,通过用户名和密码验证用户。

var loginstatus bool
var username, password string

func login(username, password string) bool {
	if username == "user123" && password == "pass123" {
		return true
	} else {
		return false
	}
}

func main() {
	fmt.Print("Username: ")
	user := bufio.NewScanner(os.Stdin)
	fmt.Print("Password: ")
	pass := bufio.NewScanner(os.Stdin)


	for user.Scan() && pass.Scan() {
		if login(user.Text(), pass.Text()) {
			fmt.Println("Signed in.")
			os.Exit(3)
		} else {
			fmt.Println("Incorrect username or password, please try again:")
		}
	}
}

这个问题可以通过将fmt.Print("Password: ")移动到for循环内部解决。这样,当输入用户名后,才会打印出"Password: "。修复后的代码如下:

package main

import (
	"bufio"
	"os"
	"fmt"
)

// 一个简单的程序,通过用户名和密码验证用户。

var loginstatus bool
var username, password string

func login(username, password string) bool {
	if username == "user123" && password == "pass123" {
		return true
	} else {
		return false
	}
}

func main() {
	fmt.Print("Username: ")
	user := bufio.NewScanner(os.Stdin)

	for user.Scan() {
		fmt.Print("Password: ")
		pass := bufio.NewScanner(os.Stdin)

		if login(user.Text(), pass.Text()) {
			fmt.Println("Signed in.")
			os.Exit(3)
		} else {
			fmt.Println("Incorrect username or password, please try again:")
		}
	}
}

修复后的代码会在输入用户名后才打印出"Password: "。

英文:

There is a program that reads two inputs from command line: username and password. The string "Password: " should be printed in console only after entering the username, but in my program it prints right away along with the first string "Username: ". How to fix this?

package main

import (
	"bufio"
	"os"
	"fmt"
)
// A simple program that verifies the user by username and password.

var loginstatus bool
var username, password string
func login(username, password string) bool {
	if username == "user123" && password == "pass123" {
		return true
	} else {
		return false
	}
}

func main() {
	fmt.Print("Username: ")
	user := bufio.NewScanner(os.Stdin)
	fmt.Print("Password: ")
	pass := bufio.NewScanner(os.Stdin)


	for user.Scan() && pass.Scan() {
		if login(user.Text(), pass.Text()) {
			fmt.Println("Signed in.")
			os.Exit(3)
		} else {
			fmt.Println("Incorrect username or password, please try again:")
		}
	}
}

答案1

得分: 5

bufio.NewScanner(os.Stdin)这一行只是创建了一个用于标准输入的新扫描器,它并不实际进行扫描,并且不会阻塞等待用户输入。直到调用Scan方法之前,它不会从标准输入中读取任何内容,此时"Username:"和"Password:"已经被打印出来。

你可能不需要两个扫描器来分别处理用户名和密码。一个扫描器应该足够了,如果你想要能够重试,你可能需要将打印"Username:"和"Password:"的部分移到for循环中,代码可能如下所示:

func main() {
    scanner := bufio.NewScanner(os.Stdin)

    for {
        fmt.Print("Username: ")
        if !scanner.Scan() {
            break
        }
        user := scanner.Text()
        fmt.Print("Password: ")
        if !scanner.Scan() {
            break
        }
        pass := scanner.Text()
        if login(user, pass) {
            fmt.Println("Signed in.")
            os.Exit(3)
        } else {
            fmt.Println("Incorrect username or password, please try again:")
        }
    }
}
英文:

The line bufio.NewScanner(os.Stdin) just creates a new scanner for stdin it does not actually do the scanning and will not block waiting for user input. It will not actually read from stdin until you call Scan by which point "Username:" and "Password:" have already been printed.

You probably don't need two scanners for username and password. One scanner should be enough and you probably want to move the printing of "Username:" and "Password:" into the for loop if you want to be able to try again so it would look something like:

func main() {
	scanner := bufio.NewScanner(os.Stdin)

	for {
		fmt.Print("Username: ")
		if !scanner.Scan() {
			break
		}
		user := scanner.Text()
		fmt.Print("Password: ")
		if !scanner.Scan() {
			break
		}
		pass := scanner.Text()
		if login(user, pass) {
			fmt.Println("Signed in.")
			os.Exit(3)
		} else {
			fmt.Println("Incorrect username or password, please try again:")
		}
	}
}

答案2

得分: 0

你需要首先声明一个新的Scanner,使用bufio.NewScanner方法,然后使用ReadString方法从os.Stdin读取数据:

func main() {
    scanner := bufio.NewReader(os.Stdin)

    fmt.Print("用户名:")
    user, _ := scanner.ReadString('\n')
    fmt.Print("密码:")
    pass, _ := scanner.ReadString('\n')

    if login(user, pass) {
        fmt.Println("登录成功。")
        os.Exit(3)
    } else {
        fmt.Println("用户名或密码错误,请重试:")
    }
}

请注意,这只是代码的翻译部分,不包括其他内容。

英文:

You need to declare first a new Scanner from bufio.NewScanner and then use the method ReadString to read the data from os.Stdin :

func main() {
	scanner := bufio.NewReader(os.Stdin)

	fmt.Print("Username: ")
	user, _ := scanner.ReadString('\n')
	fmt.Print("Password: ")
	pass, _ := scanner.ReadString('\n')

	if login(user, pass) {
		fmt.Println("Signed in.")
		os.Exit(3)
	} else {
		fmt.Println("Incorrect username or password, please try again:")
	}
}

huangapple
  • 本文由 发表于 2017年4月21日 17:47:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/43539415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定