0
我在Go中創建一個簡單的文字處理程序。在命令行中,我有兩個提示:如何將整個字符串保存爲Go中的txt文件?
$輸入標題:
$輸入正文:
程序應該將文檔保存爲一個txt文件,並將其打印到命令行。如果用戶用戶輸入一個單詞標題和一個單詞Body,該程序將起作用。但是,如果在幾個字標題的用戶類型,會出現這種情況:
$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))
}
WRT ['fmt.Scanln'](https://golang.org/pkg/fmt/#Scanln)它說「Scanln類似於掃描,但在換行停止掃描......「;所以看看['fmt.Scan'](https://golang.org/pkg/fmt/#Scan),它說:「掃描掃描從標準輸入讀取的文本,將**連續的空格分隔值**存儲爲連續的參數「。所以是的,OP有效地要求第一個字不是第一行。 –