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

Print user-entered string n times in go

WBOY
Release: 2024-02-06 08:00:07
forward
530 people have browsed it

在 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)
    }
}
Copy after login

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)
}
Copy after login

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)
    }
}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template