【问题标题】:How to print out the value in a function from a user input in Go [closed]如何从Go中的用户输入打印出函数中的值[关闭]
【发布时间】:2020-05-04 20:27:35
【问题描述】:
package main

import (
    "bufio"
    "fmt"
    "os"
)

func Option1() {
     fmt.Println("Option1")
}
func main() {
     for true {
         fmt.Println("Pleae enter text: ")
         reader := bufio.NewReader(os.Stdin)
         text, _ := reader.ReadString('\n')
         if text == "1" {
                Option1()
         }

      }
 }

所以我的代码最终将具有多功能示例:option1 option2 等。每次用户键入 1、2、3 等时,我都会尝试执行一个函数,但我的代码不会打印出任何内容在选项 1。

您的帮助将不胜感激。

【问题讨论】:

  • From the docs: "ReadString 读取直到输入中第一次出现 delim,返回一个包含 和包含分隔符 的数据的字符串。" (强调我的)。
  • 分隔符\n 包含在ReadString 返回的值中。此外,该程序丢弃从标准输入缓冲的数据。请改用Scanner。请参阅this question 了解更多信息。
  • 你也可以只检查text[:1]的值。
  • @larsks 这在所有操作系统上都不会像您期望的那样工作。使用扫描仪。
  • for { fmt.Println(prompt); if !scanner.Scan() { break }; text := scanner.Text(); /* do something with text */}

标签: function go


【解决方案1】:

基本规则是 ReadString 读取直到输入中第一次出现 delim,返回一个包含数据的字符串,直到并包括分隔符。所以我在比较之前使用 text = strings.TrimSpace(text) 修剪它。查看修改后的程序。

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func Option1() {
    fmt.Println("Option1")
}
func main() {

    for true {
        fmt.Println("Pleae enter text: ")
        reader := bufio.NewReader(os.Stdin)
        text, _ := reader.ReadString('\n')
        fmt.Println("Length of text,before trimming:", len(text))
        text = strings.TrimSpace(text)
        fmt.Println("Length of text,after trimming:", len(text))
        if text == "1" {
            Option1()
        }

    }
}

输出是

VScode> go run sofstringcompare.go
Pleae enter text: 
1
Length of text,before trimming: 3
Length of text,after trimming: 1
Option1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 2021-01-19
    相关资源
    最近更新 更多