Home  >  Article  >  Backend Development  >  How to Capture \'30 of month\' Input with fmt.Scanln?

How to Capture \'30 of month\' Input with fmt.Scanln?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 09:43:01191browse

How to Capture

Resolving "30 of month" Input Retrieval with fmt.Scanln

In the original code, utilizing fmt.Scanln posed a challenge when attempting to retrieve "30 of month" as input. The function reads space-separated tokens, resulting in the retrieval of "30" without the intended "of month."

Solutions:

  1. Using Multiple Variables for Scanning: By assigning multiple variables as arguments to fmt.Scanln, each token can be captured separately, allowing for the preservation of spaces between words.
<code class="go">var s1 string
var s2 string
fmt.Scanln(&s1, &s2)
fmt.Println(s1) // Prints "30"
fmt.Println(s2) // Prints "of month"</code>
  1. Employing bufio.Scanner for Detailed Input Parsing:
    The bufio.Scanner provides a more granular approach to input handling. By repeatedly calling scanner.Scan(), it iterates over each line of input, capturing it as a string.
<code class="go">scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
    s := scanner.Text()
    fmt.Println(s) // Prints "30 of month"
}
if err := scanner.Err(); err != nil {
    os.Exit(1)
}</code>

The above is the detailed content of How to Capture \'30 of month\' Input with fmt.Scanln?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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