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
            // ...
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分 合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备