这段Go代码有什么问题?os.Stdin是什么意思?

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

What is wrong with this go code, and what is os.Stdin?

问题

以下是您提供的代码的中文翻译:

  1. 1 package main
  2. 2
  3. 3 import (
  4. 4 "bufio"
  5. 5 "fmt"
  6. 6 "os"
  7. 7 )
  8. 8
  9. 9 func main() {
  10. 10 input := bufio.NewScanner(os.Stdin)
  11. 11 if input.Scan() {
  12. 12 if input.Text() == "1" {
  13. 13 fmt.Println("true")
  14. 14 }
  15. 15 }
  16. 16 }

这段代码的功能是询问用户输入,然后检查用户输入是否等于1。

英文:
  1. 1 package main
  2. 2
  3. 3 import (
  4. 4 "bufio"
  5. 5 "fmt"
  6. 6 "os"
  7. 7 )
  8. 8
  9. 9 func main() {
  10. 10 input := bufio.NewScanner(os.Stdin)
  11. 11 if input.Scan == 1 {
  12. 12 fmt.println("true")
  13. 13 }
  14. 14 }

I want create something that will ask for user input, then check if that user input = 1

答案1

得分: 3

扫描代码文档中说:

// Scan将扫描器推进到下一个标记,然后可以通过Bytes或Text方法访问该标记。当扫描停止时,要么是到达输入的末尾,要么是出现错误,它将返回false。

所以你可以这样做:

package main

import (
"bufio"
"fmt"
"os"
)

func main() {
input := bufio.NewScanner(os.Stdin)
if input.Scan() && input.Text() == "1" {
fmt.Println("true")
}
}

os.Stdin是使Scanner从标准输入获取输入的方法。
(https://en.wikipedia.org/wiki/Standard_streams#/media/File:Stdstreams-notitle.svg)

请注意,对于导出的函数,要注意大写字母。
在第12行,你写成了

fmt.println

应该是

fmt.Println

你可以访问
https://tour.golang.org/welcome/1
开始学习Go语言。

英文:

The Scan code documentation says:

  1. //Scan advances the Scanner to the next token, which will then be
  2. //available through the Bytes or Text method. It returns false when the
  3. //scan stops, either by reaching the end of the input or an error.

So you could do something like this:

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. )
  7. func main() {
  8. input := bufio.NewScanner(os.Stdin)
  9. if input.Scan() && input.Text() == "1" {
  10. fmt.Println("true")
  11. }
  12. }

The os.Stdin is how you make your Scanner get it's input from the stdin.
(https://en.wikipedia.org/wiki/Standard_streams#/media/File:Stdstreams-notitle.svg)

One note, pay attention for uppercase letters for exported functions.
On line 12 you wrote

  1. fmt.println

and it should be

  1. fmt.Println

You should go to
https://tour.golang.org/welcome/1
to get started with golang.

huangapple
  • 本文由 发表于 2015年11月18日 09:59:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/33770533.html
匿名

发表评论

匿名网友

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

确定