Home  >  Article  >  Backend Development  >  Print user-entered string n times in go

Print user-entered string n times in go

WBOY
WBOYforward
2024-02-06 08:00:07451browse

在 go 中打印用户输入的字符串 n 次

Question content

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.


Correct answer


Viewscanf Documentation

The two most relevant points to your question are:

  • Space separated values
  • Newline characters in the input must match newline characters in the format

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).

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete