I am a newbie and I just want to print the string entered by the user n times, but it just prints spaces n times. This is my code
package main import ( "fmt" ) func main() { var n int var s string fmt.Scanf("%d", &n) fmt.Scanf("%s", &s) for i := 0; i < n; i++ { fmt.Printf("%s\n", s) } }
Is there a way to solve this problem? Thanks.
The two most relevant points to your question are:
So if you run the application as-is, then type 20 foo
and press Enter, you will get the expected output (foo
printed 20 times). However, if you type 20
and press Enter, you will get 20 empty lines; see why let's run:
var n int var s string fmt.Scanf("%d", &n) _, err := fmt.Scanf("%s", &s) if err != nil { panic(err) }
This will panic with panic: Unexpected newline
because according to the specification "newlines in the input must match newlines in the format". Assuming you want to press Enter after each entry, you can use fmt.Scanf("%d\n", &n)
. However, as you mentioned in your comment, if you use fmt.Scanf("%s\n", &s)
and enter a string containing spaces, you will only get the first bit ( Because scanf
uses spaces as separators). < /p>
If you want to get the entire line from stdin
then the answers to this question provide some options like
func main() { var n int var s string fmt.Println("How many times? ") fmt.Scanf("%d\n", &n) fmt.Println("What to output? ") reader := bufio.NewReader(os.Stdin) s, _ = reader.ReadString('\n') for i := 0; i < n; i++ { fmt.Printf("%s", s) } }
The above is the detailed content of Print user-entered string n times in go. For more information, please follow other related articles on the PHP Chinese website!