println turning up as empty string in go

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

println turning up as empty string in go

问题

所以我写了这个小的Go程序,它给图灵机提供指令,并打印其中选定的单元格:

package main

import "fmt"
import s "strings"

func main() {
  fmt.Println(processturing("> > > + + + . ."));
}

func processturing(arguments string) string{
    result := ""
    dial := 0
    cells := make([]int, 30000)
    commands := splitstr(arguments, " ")
    for i := 0;i<len(commands);i++ {
        switch commands[i] {
        case ">":
            dial += 1
        case "<":
            dial -= 1
        case "+":
            cells[dial] += 1
        case "-":
            cells[dial] -= 1
        case ".":
            result += string(cells[dial]) + " "
        }
    }
    return result
}

//splits strings be a delimeter
func splitstr(input, delim string) []string{
    return s.Split(input, delim)
}

问题是,当运行这个程序时,控制台没有显示任何内容。它什么都没有显示。我该如何使其能够将我的函数的结果作为字符串打印出来?

英文:

So I wrote this small go program, that gives instructions to a turing machine, and prints selected cells from it:

    package main

import &quot;fmt&quot;
import s &quot;strings&quot;

func main() {
  fmt.Println(processturing(&quot;&gt; &gt; &gt; + + + . .&quot;));
}

func processturing(arguments string) string{
    result := &quot;&quot;
    dial := 0
    cells := make([]int, 30000)
    commands := splitstr(arguments, &quot; &quot;)
    for i := 0;i&lt;len(commands);i++ {
        switch commands[i] {
        case &quot;&gt;&quot;:
            dial += 1
        case &quot;&lt;&quot;:
            dial -= 1
        case &quot;+&quot;:
            cells[dial] += 1
        case &quot;-&quot;:
            cells[dial] -= 1
        case &quot;.&quot;:
            result += string(cells[dial]) + &quot; &quot;
        }
    }
    return result
}

//splits strings be a delimeter
func splitstr(input, delim string) []string{
    return s.Split(input, delim)
}

Problem is, when this is run, the console doesn't display anything. It just displays nothing. How do I make this work to fmt.println the resulting string from my function?

答案1

得分: 6

表达式string(cells[dial])会产生整数值cells[dial]的UTF-8表示。打印带引号的字符串输出以查看发生了什么:

fmt.Printf("%q\n", processturing(">>>+++..")) // 打印 "\x03 \x03"

我认为你想要整数的十进制表示:

strconv.Itoa(cells[dial])

playground示例

英文:

The expression

 string(cells[dial])

yields the UTF-8 representation of the integer value cells[dial]. Print the quoted string output to see what's going on:

 	fmt.Printf(&quot;%q\n&quot;, processturing(&quot;&gt; &gt; &gt; + + + . .&quot;)) // prints &quot;\x03 \x03 &quot;

I think you want the decimal representation of the integer:

 strconv.Itoa(cells[dial])

playground example.

huangapple
  • 本文由 发表于 2016年1月16日 09:06:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/34822405.html
匿名

发表评论

匿名网友

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

确定