我正在用 Go 创建一个简单的文字处理程序。从命令行,我有两个提示:
$输入标题:
$输入正文:
该程序应该将文档保存为 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))
}
拉丁的传说
如何将整个文档HTML作为字符串?
c#如何将数据输出到.txt文件中
如何将文件中的行转换为没有换行符的字符串?
如何在Windows批处理文件中按空格分割字符串?
相关分类