doujiang3997 2016-09-17 07:20
浏览 67
已采纳

为什么在GO语言中以下代码的输出错误

This is my code written to implement a Stack. When I execute this, it generates some different kind of output totally. A screenshot of output is attached. Why is the program generating such invalid output? Is there any mistake in the code?

package main

import "fmt"

var st [100]int
var top int

func main() {
    top = -1
    ch := 0
    temp := 0
    for true {
        fmt.Println("Enter you choice:")
        fmt.Println("1. PUSH
2. POP
3. PRINT
4. EXIT")
        fmt.Scanf("%d", &ch)
        switch ch {
        case 1:
            fmt.Println("Enter the value...")
            fmt.Scanf("%d", &temp)
            push(temp)
        case 2:
            temp = pop()
            if temp != -1 {
                fmt.Println("The popped value is ", temp)
            }
        case 3:
            print()
        case 4:
            break
        default:
            fmt.Println("Please enter a valid choice")
        }
    }
}

func print() {
    i := 0
    if top == -1 {
        fmt.Println("First insert elements into the stack")
    } else {
        fmt.Printf("The values are as follows")
        for i <= top {
            fmt.Println(st[i])
            i++
        }
    }
}

func pop() int {
    if top == -1 {
        fmt.Println("Please push values before popping")
        return -1
    }
    temp := st[top]
    top--
    return temp
}

func push(n int) {
    top++
    st[top] = n
}

Screen shot of the output:

enter image description here

  • 写回答

1条回答 默认 最新

  • dqroktbn005028 2016-09-17 07:32
    关注

    The problem is that you want it to work like you enter a value and press <kbd>Enter</kbd> which generates a newline character, and you try to scan it using fmt.Scanf(). Quoting from its doc:

    Newlines in the input must match newlines in the format.

    So if you want to use fmt.Scanf(), the format string must include a newline . But since yours doesn't, the newline is not consumed, so the next line to read the value will automatically proceed.

    Easy fix: add to the format string:

    fmt.Println("Enter you choice:")
    fmt.Println("1. PUSH
    2. POP
    3. PRINT
    4. EXIT")
    fmt.Scanf("%d
    ", &ch)
    

    And:

    fmt.Println("Enter the value...")
    fmt.Scanf("%d
    ", &temp)
    

    An alternative is to simply use fmt.Scanln() which automatically parses a whole line:

    fmt.Println("1. PUSH
    2. POP
    3. PRINT
    4. EXIT")
    fmt.Scanln(&ch)
    
    // ... 
    
    fmt.Println("Enter the value...")
    fmt.Scanln(&temp)
    

    Also, fmt.Scanf() and fmt.Scanln() return the number of successfully scanned values and an error. Be sure to check those to see if scanning succeeded.

    Another error you have in your code is the Exit functionality: you used break statement in the case 4 branch. break will only break the switch and not the for! So use a return instead of break:

        case 4:
            return
    

    Another fix could be to use labels, also note that for true { ... } is equivalent with for { ... } (you can omit the true):

    mainloop:
        for {
            // ...
            switch ch {
            // ...
            case 4:
                break mainloop
            // ...
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集