1 回答
TA贡献1789条经验 获得超8个赞
使用bufio.ReadString而不是怎么样fmt.Scanln?不是 100% Scanln 是如何工作的,但我很确定问题来自对该功能的滥用。bufio 示例:
package main
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
)
// Document represent the document's data.
type Document struct {
Title string
Body []byte
}
// Save dumps document as txt file on disc.
func (p *Document) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
// loadPage loads a document from disc.
func loadPage(title string) (*Document, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return &Document{Title: title, Body: body}, nil
}
// Input document title and body.
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Title: ")
title, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
title = strings.TrimSpace(title)
fmt.Print("Enter Body: ")
body, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
body = strings.TrimSpace(body)
//Save document and display on command line
p1 := &Document{Title: title, Body: []byte(body)}
if err := p1.save(); err != nil {
log.Fatal(err)
}
p2, err := loadPage(title)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(p2.Body))
}
- 1 回答
- 0 关注
- 489 浏览
添加回答
举报