dongzouxigu12345 2019-03-03 16:06
浏览 7
已采纳

scanfl声明变量超出功能

I need an help to get out of a corner, because I don't understand the logic behind a problem I am having.

I need to ask multiple times a user input, so logically I am creating a function like:

func askstuff() {
    fmt.Println("Write something:")
    var input string
    fmt.Scanln(&input)
}

now I need to get the user input into a variable from the main() function, but I have a non-declarative matter and a brain issue....in fact I was expecting to do something like, but it is wrong

func main() {
    askstuff()
    println askstuff(input)
}

I have been reading all posts and docs and I understood that instead of a function, I should use a declarative variable out of main(), in the body, before main(). It works like a charm only if there is an hard coded fixed value but it doesn't with Scanln interactive console input.

I need to execute so many time askstuff(), that it will drive me nut without a separate class/function, but I also need to close the input into a variable within main() function, out of askstuff() function, to be able to work on it.

I am 100% ok with an RTFM reply if you give me one example that doesn't use a fixed hard coded value but use a user console interaction by scanln.

All book examples never use a scanln input, always a fixed declarative variable out of main () in the body.

Am I running in a specific scanln limitation? is a design concept matter with my logic? or there are better ways?

Please don't just give me just the snippet on how to fix the matter, explain me where and why my logic is wrong, so to understand it and don't repeat the error in the future.

  • 写回答

1条回答 默认 最新

  • dongxing7318 2019-03-03 16:54
    关注

    Return the string from askstuff and use as needed in the caller:

    func askstuff() string {
        fmt.Println("Input to exit digit X:")
        var input string
        fmt.Scanln(&input)
        return input
    }
    
    func main() {
        x := askstuff()
        fmt.Println(x)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line