如何在 Go 中将整个字符串保存为 txt 文件?

我正在用 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))

}


三国纷争
浏览 495回答 1
1回答

拉丁的传说

使用bufio.ReadString而不是怎么样fmt.Scanln?不是 100% Scanln 是如何工作的,但我很确定问题来自对该功能的滥用。bufio 示例:package mainimport (        "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))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go