我正在用Go创建一个简单的文字处理程序。在命令行中,我有两个提示:
$Enter 标题:
$Enter体:
该程序应该将文档另存为 txt 文件并将其打印到命令行。如果用户用户键入一个单词的标题和一个单词的正文,则程序将起作用。但是,如果用户键入几个单词的标题,就会发生这种情况:
$Enter Title: Here is a title
$Enter Body: s
$ title
-bash: title: command not found
这是我到目前为止的代码:
package main
import (
"fmt"
"io/ioutil"
)
//Create struct for a document
type Document struct {
Title string
Body []byte
}
//Save document as txt file
func (p *Document) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
//Load document
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() {
fmt.Print("Enter Title: ")
var Title string
fmt.Scanln(&Title)
fmt.Print("Enter Body: ")
var Body []byte
fmt.Scanln(&Body)
//Save document and display on command line
p1 := &Document{Title: Title, Body: []byte(Body)}
p1.save()
p2, _ := loadPage(Title)
fmt.Println(string(p2.Body))
}
使用 bufio.ReadString
而不是 fmt.Scanln
怎么样?不是 100% Scanln 的工作方式,但我很确定问题来自对该函数的滥用。布菲奥的例子:
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))
}