Hello, I am trying to remove spaces from a string that I am reading in from the command console. However, it does not appear that the strings.Trim() and strings.TrimSpace() functions are working correctly.
For instance giving my following code:
type employee struct {
name string
age int
salary int64 //64-bit integer assignment to salary
}
func main() {
var employees [5]employee
inputReader := bufio.NewReader(os.Stdin)
for i := range employees {
fmt.Println("Please enter Employee Information", i+1, "'s name")
fmt.Println("Please do so using a ; value separated sequence")
fmt.Println("E.g. Patrick Stroud; 48; 140565")
fmt.Print(">")
userString, err := inputReader.ReadString('\n')
if err != nil {
log.Fatal(err) //Equivalent to fmt.Println(err)
}
userString = strings.Trim(userString, "\n")
userString = strings.TrimSpace(userString)
userInfo := strings.Split(userString, ";")
employees[i].name = userInfo[0]
employees[i].age, _ = strconv.Atoi(userInfo[1]) //error checking not done here on purpose
employees[i].salary, _ = strconv.ParseInt(userInfo[2], 10, 64) //error checking not done to not cause error
}
fmt.Println("# Employee Name\t Age\t Salary")
fmt.Println("=============================================")
p := message.NewPrinter(language.English)
for i := range employees {
fmt.Printf("%s\t", employees[i].name)
fmt.Printf("%d\t", employees[i].age)
p.Printf("%d\n", employees[i].salary)
}
}
The Following output is returned:
Please enter Employee Information 1 's name
Please do so using a ; value separated sequence
E.g. Patrick Stroud; 48; 140565
>Patrick Stroud; 48; 140565
Please enter Employee Information 2 's name
Please do so using a ; value separated sequence
E.g. Patrick Stroud; 48; 140565
>Ursula Spencer; 27; 36450
Please enter Employee Information 3 's name
Please do so using a ; value separated sequence
E.g. Patrick Stroud; 48; 140565
>Clifton Stillman; 65; 99900
Please enter Employee Information 4 's name
Please do so using a ; value separated sequence
E.g. Patrick Stroud; 48; 140565
>William Reynolds; 37; 77550
Please enter Employee Information 5 's name
Please do so using a ; value separated sequence
E.g. Patrick Stroud; 48; 140565
>Dean Niles; 53; 120000
# Employee Name Age Salary
=============================================
Patrick Stroud 0 0
Ursula Spencer 0 0
Clifton Stillman 0 0
William Reynolds 0 0
Dean Niles 0 0
As one can see the name field still contains a space and it should not due to the line of code found on line 52:
userString = strings.TrimSpace(userString)
Why is this occuring?