"Enter a command and data: " - this prints twice instead of once and I'm unable to figure out why
The plan is "Enter the maximum number of notes: " prints to CLI, get and saves user input, then print "Enter a command and data: " prints. But it keeps printing twice on the same line.
Here is the code below.
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)
}
}
}
CodePudding user response:
I assume that you are executing this on a Windows system.
I researched for this issue and found that there is an issue with Windows system with 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')
This is happening because EOL in Windows system is represented by '\r\n'
For more info on this https://groups.google.com/g/golang-nuts/c/hWoESdeZ398
So in your case if we change the line line, _ := reader.ReadString('\r')
and I tried executing this on Windows and it solved your problem.