登录
首页 >  Golang >  Go问答

Golang在我的内存笔记本上的第三阶段

来源:stackoverflow

时间:2024-02-06 11:00:22 170浏览 收藏

大家好,我们又见面了啊~本文《Golang在我的内存笔记本上的第三阶段》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

“输入命令和数据:” - 这会打印两次而不是一次,我无法弄清楚为什么

计划是“输入最大注释数:”打印到 cli,获取并保存用户输入,然后打印“输入命令和数据:”打印。但它总是在同一行上打印两次。

下面是代码。

package main

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

func readFromStdin() string {
    fmt.Print("Enter a command and data: ")
    reader := bufio.NewReader(os.Stdin)
    line, _ := reader.ReadString('\n')
    //line = line[:len(line)-2]
    line = strings.TrimSpace(line)

    return line
}

func main() {
    var notes []string
    var maximumNotes int

    for {
        if maximumNotes <= 0 {
            fmt.Print("Enter the maximum number of notes: ")
            _, _ = fmt.Scan(&maximumNotes)
        }
        line := readFromStdin()
        var joinedNote string
        var note []string

        splittedString := strings.Split(line, " ")
        if splittedString[0] == "create" && len(notes) >= maximumNotes {
            fmt.Println("[Error] Notepad is full")
        }
        if splittedString[0] == "create" && len(splittedString) <= 1 {
            fmt.Println("[Error] Missing note argument")
        }
        if splittedString[0] == "create" && len(splittedString) > 1 && len(notes) < maximumNotes {
            i := 1
            for ; i < len(splittedString); i++ {
                note = append(note, splittedString[i])
            }
            joinedNote = strings.Join(note, " ")
            notes = append(notes, joinedNote)
            fmt.Println("[OK] The note was successfully created")
        }
        if splittedString[0] == "list" && len(notes) <= 0 {
            fmt.Println("[Info] Notepad is empty")
        }
        if splittedString[0] == "list" {
            for i, noteList := range notes {
                //newNote := strings.TrimSpace(noteList)
                fmt.Printf("[Info] %d: %s\n", i+1, noteList)
            }
        }
        if splittedString[0] == "clear" {
            notes = nil
            fmt.Println("[OK] All notes were successfully deleted")
        }

        if splittedString[0] == "exit" {
            fmt.Println("[Info] Bye!")
            os.Exit(0)
        }
    }
}

正确答案


我假设您正在 windows 系统上执行此操作。

我研究了这个问题,发现有一个问题 windows系统用bufio.readstring

# '\n' will be added in the next reading function, if any
buf.ReadString('\r')

# you finish with the string that you want plus '\r' at the end
buf.ReadString('\n')

发生这种情况是因为 windows 系统中的 eol 由 '\r\n' 表示

有关此https://groups.google.com/g/golang-nuts/c/hWoESdeZ398的更多信息

因此,在您的情况下,如果我们更改行 line, _ := reader.readstring('\r')

我尝试在 windows 上执行此操作,它解决了您的问题。

今天关于《Golang在我的内存笔记本上的第三阶段》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>