I use this, to collect a input and display the input then, but when I do it like this the "something" text will be displayed in a new line, but I want the text to be displayed in the same line, any ideas?
func main() {
fmt.Println("Example")
print("example: ")
in := bufio.NewReader(os.Stdin);
input, err := in.ReadString('
');
if err != nil {
fmt.Println("Error: ", err)
}
fmt.Println(input, "something")
}
fmt.Println()
automatically appends a newline to the end of it's output.
You could try using Printf, which takes a "format string" and a list of inputs.
An example would be:
func main() {
fmt.Println("Example")
print("example: ")
in := bufio.NewReader(os.Stdin);
input, err := in.ReadString('
');
if err != nil {
fmt.Println("Error: ", err)
}
fmt.Printf("something : %s", input)
}
In this case, %s is a placeholder for a string type. All the placeholders can be found in the fmt godoc: http://golang.org/pkg/fmt/
Also if the input itself has a newline at the end, you can use Trim
from the package strings
to pull off the character.
Trim the newline from input
. For example,
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
fmt.Println("Example")
print("example: ")
in := bufio.NewReader(os.Stdin)
input, err := in.ReadString('
')
if err != nil {
fmt.Println("Error: ", err)
return
}
fmt.Println(strings.TrimRight(input, "
"), "something")
}
Input/Output:
Example
example: some input
some input something
On windows (not sure if that is relevant) none of the previous answers worked for me. So here's the resolution I found on: https://groups.google.com/d/msg/golang-nuts/hWoESdeZ398/qDbTogJhj88J which links to https://play.golang.org/p/_9N_RwmBvd
The basic idea is that rather than using strings.TrimRight(input, " ")
you would include a character, like
strings.TrimRight(input, " ")
This fixes the OPs issue.
OP code with fixed input stripping!
func main() {
fmt.Println("Example")
print("example: ")
in := bufio.NewReader(os.Stdin);
input, err := in.ReadString('
');
if err != nil {
fmt.Println("Error: ", err)
}
fmt.Println(strings.TrimRight(input, "
"), "something")
}
PS: Sorry for the necro I'm just hoping to save someone from wasting 20 minutes googling!