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

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

Write to stdout without creating a buffer

问题

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

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

  1. for i, i < size; i++ {
  2. b = a[i] + i * 10
  3. fmt.Print(string((b)))
  4. }
  5. 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?

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

答案1

得分: 9

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

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

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

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

答案2

得分: 1

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

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

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

  1. 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:

确定