写入文件int转换为字符串

时间:2016-06-03 17:32:38

标签: go file-writing

我只想简单地写一个从int转换的字符串。但f.WriteString而不是数字从ASCII代码表中写入符号。

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

但反而得到了“noReport =〠nr3h= i nr2h =¢nr1h =& ok =䈃”

2 个答案:

答案 0 :(得分:2)

要获取包含整数的字符串,我建议使用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

答案 1 :(得分:1)

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&#39; answer