1 回答
TA贡献1790条经验 获得超9个赞
你必须使用strings.TrimSpace而不是strings.Replace 因为在你的代码中你没有删除回车\r
请参阅下面更正后的代码。
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
}
添加回答
举报