我一直無法找到這個地方(或者我只是不明白它)。我正在閱讀由空格分隔的文件中的數字列表。即該文件看起來像「1 4 0 0 2 5 ... etc」,我希望它以一個數組的形式(或者,最好是一個2維數組,每個新行也分開)。我該如何去做這件事?如何在Go中將一串整數轉換爲數組?
這是我到目前爲止的代碼 - 很多都是從我找到的教程中獲得的,所以我沒有完全理解它。它讀取文件就好了,並返回一個字符串。 側面問題:當我打印字符串時,我在輸出結尾處得到:%!(EXTRA) 有誰知道如何解決這個問題?我假設它將最後一個零字符放在返回字符串中,但我不知道如何解決這個問題。
package main
import (
"fmt"
"os"
)
func read_file(filename string) (string, os.Error) {
f, err := os.Open(filename)
if err != nil {
return "", err
}
defer f.Close() // f.Close will run when we're finished.
var result []byte
buf := make([]byte, 100)
for {
n, err := f.Read(buf[0:])
result = append(result, buf[0:n]...) // append is discussed later.
if err != nil {
if err == os.EOF {
break
}
return "", err // f will be closed if we return here.
}
}
return string(result), nil // f will be closed if we return here.
}
func print_board() {
}
func main() {
fmt.Printf(read_file("sudoku1.txt")) // this outputs the file exactly,
// but with %!(EXTRA <nil>) at the end.
// I do not know why exactly
}
非常感謝您提供的任何幫助。
-W
非常感謝,這非常有幫助。我對語言有了更好的理解。 –