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
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!

GoroutinesarefunctionsormethodsthatrunconcurrentlyinGo,enablingefficientandlightweightconcurrency.1)TheyaremanagedbyGo'sruntimeusingmultiplexing,allowingthousandstorunonfewerOSthreads.2)Goroutinesimproveperformancethrougheasytaskparallelizationandeff

ThepurposeoftheinitfunctioninGoistoinitializevariables,setupconfigurations,orperformnecessarysetupbeforethemainfunctionexecutes.Useinitby:1)Placingitinyourcodetorunautomaticallybeforemain,2)Keepingitshortandfocusedonsimpletasks,3)Consideringusingexpl

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

Use the recover() function in Go to recover from panic. The specific methods are: 1) Use recover() to capture panic in the defer function to avoid program crashes; 2) Record detailed error information for debugging; 3) Decide whether to resume program execution based on the specific situation; 4) Use with caution to avoid affecting performance.

The article discusses using Go's "strings" package for string manipulation, detailing common functions and best practices to enhance efficiency and handle Unicode effectively.

The article details using Go's "crypto" package for cryptographic operations, discussing key generation, management, and best practices for secure implementation.Character count: 159

The article details the use of Go's "time" package for handling dates, times, and time zones, including getting current time, creating specific times, parsing strings, and measuring elapsed time.

Article discusses using Go's "reflect" package for variable inspection and modification, highlighting methods and performance considerations.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
