Home > Back-end >  Not printing series of variable in golang
Not printing series of variable in golang

Time:03-26

I'm learning Golang got some weird output using go v1.18 when I print firstName, lastName, birthday, created only got result as created I have printed declaring variable and printing whole thing again it works fine the problem is with var reader = bufio.NewReader(os.Stdin)

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
    "time"
)

var reader = bufio.NewReader(os.Stdin)

func main() {
    firstName := getUserData("Enter First Name: ")
    lastName := getUserData("Enter Last Name: ")
    birthdate := getUserData("Enter Date of Birth: ")
    created := time.Now()

    fmt.Println(firstName, lastName, birthdate, created) //only prints created
    fmt.Println(firstName) // prints firstName
    fmt.Println(lastName) // prints lastName
    fmt.Println(birthdate) // prints birthdate
    fmt.Println(created) // prints created
}

func getUserData(promptText string) string {
    fmt.Print(promptText)
    userInput, _ := reader.ReadString('\n')
    cleanedInput := strings.Replace(userInput, "\n", "", -1)
    return cleanedInput
}

CodePudding user response:

you have to use strings.TrimSpace instead of strings.Replace because in your code you did not remove the Carriage return \r

See the corrected code below.

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
    "time"
)

var reader = bufio.NewReader(os.Stdin)

func main() {
    firstName := getUserData("Enter First Name: ")
    lastName := getUserData("Enter Last Name: ")
    birthdate := getUserData("Enter Date of Birth: ")
    created := time.Now()

    fmt.Println(firstName, lastName, birthdate, created) //will print all
    fmt.Println(firstName)                               // prints firstName
    fmt.Println(lastName)                                // prints lastName
    fmt.Println(birthdate)                               // prints birthdate
    fmt.Println(created)                                 // prints created
}

func getUserData(promptText string) string {
    fmt.Print(promptText)
    userInput, _ := reader.ReadString('\n')
    cleanedInput := strings.TrimSpace(userInput)

    return cleanedInput
}
  •  Tags:  
  • go
  • Related