Home > Blockchain >  A simple CLI that receives input from users
A simple CLI that receives input from users

Time:09-22

When I type in the command, give a space before hitting the enter button, it works fine, but it doesn't work if there is no space

I have tried several ways to fix this, but have been unable to

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)
    func main() {
        var notes []string
        for {
            fmt.Print("Enter a command and data: ")
            reader := bufio.NewReader(os.Stdin)
            line, _ := reader.ReadString('\n')
            var joinedNote string
            var note []string
    
            splittedString := strings.Split(line, " ")
    
            if splittedString[0] == "create" && len(splittedString) > 1 {
                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" || string(line) == "list" {
                for i, noteList := range notes {
                    newNote := strings.TrimSpace(noteList)
                    fmt.Printf("[Info] %d: %s!\n", i, newNote)
                }
            }
            if splittedString[0] == "clear" || line == "clear" {
                notes = nil
                fmt.Println("[OK] All notes were successfully deleted")
            }
    
            if splittedString[0] == "exit" || line == "exit" {
                fmt.Println("[Info] Bye!")
                os.Exit(0)
            }
        }
    }

CodePudding user response:

The reason for this is that you are including the \n in line you capture from the user and without the space after it, the \n gets tagged onto the word you are looking for ( create\n does not equal create ). Easiest way to fix this is to manually remove the trailing \n with line = line[:len(line)-1].

Here is a little more a deep dive. First the ReadString method says it included the delimiter, in this case \n, you give it:

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. So we know line will always have the \n at the end of it unless you manually remove it.

Your code worked when the word was followed by a space because your strings.Split(line," ") turned the input create \n into {"create","\n"}.

  • Related