写入文件 int 转换为字符串

Writing to file int converted to string

我只想简单地将一个从 int 转换而来的字符串写入文件。但是 f.WriteString 而不是数字写一个来自 ASCII 码的符号 table.

我预计 "noReport = 12320 nr3h = 105 nr2h = 162 nr1h = 38 ok = 16899"

却得到了"noReport = 〠 nr3h = i nr2h = ¢ nr1h = & ok = 䈃"

https://play.golang.org/p/QAXJ4aJBy3

fmt.Printf("os.StdOut is %T\n", os.Stdout)
os.Stdout.WriteString("noReport = 12320 nr3h = 105 nr2h = 162 nr1h = 38 ok = 16899 \n")
os.Stdout.WriteString("12320")

//Output
//os.StdOut is *os.File
//noReport = 12320 nr3h = 105 nr2h = 162 nr1h = 38 ok = 16899 
//12320

对我来说很好用。

请给我们您的代码。

UDP

string(noReport), noReport 是整数吧?这是预期的行为。

使用strconv.Itoa(noReport)。

noReport := 12320
nr3h := 105
nr2h := 162
nr1h := 38
ok := 16899
os.Stdout.WriteString("noReport = "+ strconv.Itoa(noReport) + " nr3h = " + strconv.Itoa(nr3h)+ " nr2h = "+ strconv.Itoa(nr2h)+ " nr1h = "+ strconv.Itoa(nr1h) + " ok = "+ strconv.Itoa(ok)+ "\n") 

或 evanmcdonnal 的

要获取带有整数的字符串,我建议使用 fmt.Sprintf

会是这样的;

s := fmt.Sprintf("noReport = %d nr3h = %d nr2h = %d nr1h = %d ok = 16899", 12320, 162, 38)

这会将值 "noReport = 12320 nr3h = 105 nr2h = 162 nr1h = 38 ok = 16899" 分配给 s