在不创建缓冲区的情况下将内容写入标准输出。

huangapple go评论64阅读模式
英文:

Write to stdout without creating a buffer

问题

在循环中进行一些计算,然后我想从字节数组中打印一个字符串值,一旦循环结束,打印一个新行。

使用fmt.Print会分配一个缓冲区,但我只想将字符打印到标准输出。有没有办法做到这一点?

for i, i < size; i++ {
    b = a[i] + i * 10
    fmt.Print(string((b)))
}
fmt.Println()
英文:

Inside a loop I do some calculations and then I want to print a string value from a byte array, once the loop is done print a new line.

Using fmt.Print will allocate a buffer, but all I want to do is print the character to stdout. Is there a way to do that?

for i, i &lt; size; i++ {
	b = a[i] + i * 10
	fmt.Print(string((b)))
}
fmt.Println()

答案1

得分: 9

你可以通过向os.Stdout文件写入来实现这一点:

var buff [1]byte
for i := 0; i < size; i++ {
    b := a[i] + i * 10
    buff[0] = b
    os.Stdout.Write(buff[:])
}
buff[0] = '\n'
os.Stdout.Write(buff[:])
英文:

You can do this by simply writing to the os.Stdout file:

var buff [1]byte
for i, i &lt; size; i++ {
    b = a[i] + i * 10
    buff[0] = b
    os.Stdout.Write(buff[:])
}
buff[0] = &#39;\n&#39;
os.Stdout.Write(buff[:])

答案2

得分: 1

你可以使用fmt.Printf代替你的fmt.Print(string((b))),像这样:

fmt.Printf("%c", b)
英文:

You can use fmt.Printf instead of your fmt.Print(string((b))) like so:

 fmt.Printf(&quot;%c&quot;, b)

huangapple
  • 本文由 发表于 2016年12月6日 05:15:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/40983475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定