2015-06-19 31 views
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)) 
} 

回答

0

有關使用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

WRT ['fmt.Scanln'](https://golang.org/pkg/fmt/#Scanln)它說「Scanln類似於掃描,但在換行停止掃描......「;所以看看['fmt.Scan'](https://golang.org/pkg/fmt/#Scan),它說:「掃描掃描從標準輸入讀取的文本,將**連續的空格分隔值**存儲爲連續的參數「。所以是的,OP有效地要求第一個字不是第一行。 –

相關問題