Sequential output and input of strings in Go

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

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:")
        }
    }
}

      

+3


source to share


2 answers


The line bufio.NewScanner(os.Stdin)

just creates a new scanner for stdin, it doesn't actually scan and block waiting for user input. It won't actually read from stdin until you name the Scan

one that has already been typed "Username:" and "Password:".

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



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:")
        }
    }
}

      

+5


source


You need to first declare a new scanner from bufio.NewScanner and then use the ReadString method to read 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:")
    }
}

      

0


source







All Articles