简体   繁体   English

为什么这是GO语言下面代码的输出错误

[英]Why is this the output of the following code wrong in GO language

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\n2. POP\n3. PRINT\n4. 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:输出的屏幕截图:

在此处输入图片说明

The problem is that you want it to work like you enter a value and press Enter which generates a newline character, and you try to scan it using fmt.Scanf() .问题是您希望它像输入一个值并按Enter 键那样工作,这会生成一个换行符,然后您尝试使用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 \\n .因此,如果您想使用fmt.Scanf() ,格式字符串必须包含换行符\\n But since yours doesn't, the newline is not consumed, so the next line to read the value will automatically proceed.但是由于您的没有,换行符不会被消耗,因此读取值的下一行将自动继续。

Easy fix: add \\n to the format string:简单修复:将\\n添加到格式字符串中:

fmt.Println("Enter you choice:")
fmt.Println("1. PUSH\n2. POP\n3. PRINT\n4. EXIT")
fmt.Scanf("%d\n", &ch)

And:和:

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

An alternative is to simply use fmt.Scanln() which automatically parses a whole line:另一种方法是简单地使用fmt.Scanln()自动解析整行:

fmt.Println("1. PUSH\n2. POP\n3. PRINT\n4. 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.此外, fmt.Scanf()fmt.Scanln()返回成功扫描值的数量和错误。 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.您代码中的另一个错误是 Exit 功能:您在case 4分支中使用了break语句。 break will only break the switch and not the for ! break只会破坏switch而不是for So use a return instead of break :所以使用return而不是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 ):另一个解决方法可能是使用标签,还要注意for true { ... }等同于for { ... } (您可以省略true ):

mainloop:
    for {
        // ...
        switch ch {
        // ...
        case 4:
            break mainloop
        // ...
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM