cin := bufio.NewReader(os.Stdin)
fmt.Println("Enter person's name:")
person, err := cin.ReadString('\n')
if err != nil {
fmt.Println(err)
}else{
fmt.Print(person)
fmt.Println(len(person))
}
person = strings.TrimSuffix(person,"\n")
fmt.Println("Enter person's quote:")
quote, err := cin.ReadString('\n')
if err != nil {
fmt.Println(err)
}else{
fmt.Print(quote)
fmt.Println(len(quote))
}
quote = strings.TrimSuffix(quote,"\n")
fmt.Println("------------")
fmt.Print(person)
fmt.Print(len(person))
fmt.Print(quote)
fmt.Print(len(quote))
My intention is to read a string and trim the \n trailing behind it since ReadString will include the \n. But using TrimSuffix(person,'\n') will not work and I don't understand why. Using string defined in program works but not user input. It will give strange behavior like returning an empty string and other undesired behaviors. I then checked the length of the string obtained from ReadString. E.g. user input: "abc" the length will be 5. I don't understand why. Can anyone enlightens me? I managed to achieve the intention using TrimSpace but I want to know what's wrong with this approach too.
I think it's because the first 4abc got overwritten by the later one. I would expect it to be 3abc.
CodePudding user response:
If your string doesn’t contain white space, you can use fmt.Scanln
, like so:
var input string
fmt.Println("Enter a string:")
fmt.Scanln(&input)
If it contains white space:
fmt.Println("Enter a string:")
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() { // returns bool value
input := scanner.Text()
}
CodePudding user response:
I just tried your code on Goland and I modified this line:
person = strings.TrimSuffix(person,"\n")
and I obtained this result
Enter person's name:
abc
abc
4
Enter person's quote:
abc
abc
4
------------
abc3abc3
Everything is correct here, can you explain in details what do you have as result and what do you expect?