从标准输入读取一个整数。

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

Reading an integer from standard input

问题

我如何在Go中使用fmt.Scanf函数从标准输入获取整数输入?

如果无法使用fmt.Scanf完成此操作,那么读取单个整数的最佳方法是什么?

英文:

How do I use the fmt.Scanf function in Go to get an integer input from the standard input?

If this can't be done using fmt.Scanf, what's the best way to read a single integer?

答案1

得分: 148

http://golang.org/pkg/fmt/#Scanf

Go中的所有包都有很好的文档。

话虽如此,我相信

func main() {
    var i int
    _, err := fmt.Scanf("%d", &i)
}

可以解决问题。

英文:

http://golang.org/pkg/fmt/#Scanf

All the included libraries in Go are well documented.

That being said, I believe

func main() {
    var i int
    _, err := fmt.Scanf("%d", &i)
}

does the trick

答案2

得分: 60

另一种更简洁的替代方法是只使用fmt.Scan

package main

import "fmt"

func main() {
    var i int
    fmt.Scan(&i)
    fmt.Println("从标准输入读取数字", i)
}

这种方法利用参数的类型反射来确定输入应该如何解析。

http://golang.org/pkg/fmt/#Scan

英文:

An alternative that can be a bit more concise is to just use fmt.Scan:

package main

import "fmt"

func main() {
    var i int
    fmt.Scan(&i)
    fmt.Println("read number", i, "from stdin")
}

This uses reflection on the type of the argument to discover how the input should be parsed.

http://golang.org/pkg/fmt/#Scan

答案3

得分: 6

这是我的“快速IO”方法,用于读取正整数。可以通过位移和提前布局内存来改进。

package main

import (
    "io/ioutil"
    "bufio"
    "os"
    "strconv"
)


func main() {
    out := bufio.NewWriter(os.Stdout)
    ints := getInts()
    var T int64
    T, ints = ints[0], ints[1:]
    ..
    out.WriteString(strconv.Itoa(my_num) + "\n")
    out.Flush()
}

func getInts() []int64 {
    //假设为正整数。如果有负数,请检查v。
    var buf []byte
    buf, _ = ioutil.ReadAll(os.Stdin)
    var ints []int64
    num := int64(0)
    found := false
    for _, v := range buf {
        if '0' <= v && v <= '9' {
            num = 10*num + int64(v - '0') //这里可以使用位移。
            found = true
        } else if found {
            ints = append(ints, num)
            found = false
            num = 0
        }
    }
    if found {
        ints = append(ints, num)
        found = false
        num = 0
    }
    return ints
}
英文:

Here is my "Fast IO" method for reading positive integers. It could be improved with bitshifts and laying out memory in advance.

package main

import (
	&quot;io/ioutil&quot;
	&quot;bufio&quot;
	&quot;os&quot;
	&quot;strconv&quot;
)


func main() {
	out := bufio.NewWriter(os.Stdout)
	ints := getInts()
	var T int64
	T, ints = ints[0], ints[1:]
	..
	out.WriteString(strconv.Itoa(my_num) + &quot;\n&quot;)
    out.Flush()
	}
}

func getInts() []int64 {
    //assumes POSITIVE INTEGERS. Check v for &#39;-&#39; if you have negative.
	var buf []byte
	buf, _ = ioutil.ReadAll(os.Stdin)
	var ints []int64
	num := int64(0)
	found := false
	for _, v := range buf {
		if &#39;0&#39; &lt;= v &amp;&amp; v &lt;= &#39;9&#39; {
			num = 10*num + int64(v - &#39;0&#39;) //could use bitshifting here.
			found = true
		} else if found {
			ints = append(ints, num)
			found = false
			num = 0
		}
	}
	if found {
		ints = append(ints, num)
		found = false
		num = 0
	}
	return ints
}

答案4

得分: 5

Golang fmt.Scan比Golang fmt.Scanf更简单(比Clang scanf更简单)

如果fmt.Scan出现错误,即不为nil,则记录日志并返回

#1 读取单个变量:

import (
	"fmt"
    "log"
)

var i int
if _, err := fmt.Scan(&i); err != nil {
	log.Print("  读取i失败,原因是", err)
	return
}

fmt.Println(i)

#2 读取多个变量:

import (
	"fmt"
    "log"
)

var i, j, k int  
if _, err := fmt.Scan(&i, &j, &k); err != nil {
	log.Print("  读取i、j和k失败,原因是", err)
	return
}

fmt.Println(i, j, k)

祝你好运

示例来源:http://www.sortedinf.com/?q=golang-in-1-hour

英文:

Golang fmt.Scan is simpler than Golang fmt.Scanf (which is simpler than Clang scanf)

If fmt.Scan errors i.e. if not nil, log & return

#1 Read single variable:

import (
	&quot;fmt&quot;
    &quot;log&quot;
)

var i int
if    _, err := fmt.Scan(&amp;i);    err != nil {
	log.Print(&quot;  Scan for i failed, due to &quot;, err)
	return
}

fmt.Println(i)

#2 Read multiple variables:

import (
	&quot;fmt&quot;
    &quot;log&quot;
)

var i, j, k int  
if    _, err := fmt.Scan(&amp;i, &amp;j, &amp;k);    err != nil {
	log.Print(&quot;  Scan for i, j &amp; k failed, due to &quot;, err)
	return
}

fmt.Println(i, j, k)

Best of luck

Example from: http://www.sortedinf.com/?q=golang-in-1-hour

答案5

得分: 0

你可以使用fmt.Scanf和格式说明符来读取整数。整数的格式说明符是%d。所以你可以像下面这样使用标准输入。

func main() {
    var someVar int
    fmt.Scanf("%d", &someVar)
}

或者你可以像下面这样使用fmt.Scanfmt.Scanln

func main() {
   var someVar int
   fmt.Scanln(&someVar)
}
英文:

You can use fmt.Scanf with a format specifier. The format specifier for the integer is %d. So you can use standard input like below.

func main() {
    var someVar int
    fmt.Scanf(&quot;%d&quot;, &amp;someVar)
}

or else you can use fmt.Scan or fmt.Scanln as below.

func main() {
   var someVar int
   fmt.Scanln(&amp;someVar)
}

答案6

得分: 0

你也可以使用bufio.NewReader从标准输入读取一个整数。

下面的程序:

  • 提示输入一个整数

  • 创建一个bufio.Reader来从标准输入读取

  • 读取输入直到遇到换行符'\n'(注意,这只会读取一个整数。空格分隔的值将不起作用)

  • 移除换行符

  • 将字符串转换为整数

package main

import (
	"fmt"
	"bufio"
	"os"
	"strconv"
	"strings"
)

func getInt() error {
	fmt.Println("输入一个整数")
	userInput  := bufio.NewReader(os.Stdin)
	userVal, err := userInput.ReadString('\n')
	if err != nil {
		return err
	}

	input := strings.TrimSpace(userVal)
	intVal, err := strconv.Atoi(input)
	if err != nil {
		return err
	}

	fmt.Printf("你输入的是:%d\n", intVal)
	return nil
}

func main() {
	getInt()
}
英文:

You could also use bufio.NewReader to read an integer from the standard input.

The below program:

  • Prompts for an integer input

  • Creates a bufio.Reader to read from standard input

  • Reads input till it encounters a newline character &#39;\n&#39; (Note that this will only read a single integer. Space separated values will not work)

  • Removes the newline character

  • Converts string to int

package main

import (
	&quot;fmt&quot;
	&quot;bufio&quot;
	&quot;os&quot;
	&quot;strconv&quot;
	&quot;strings&quot;
)

func getInt() error {
	fmt.Println(&quot;Enter an integer&quot;)
	userInput  := bufio.NewReader(os.Stdin)
	userVal, err := userInput.ReadString(&#39;\n&#39;)
	if err != nil {
		return err
	}

	input := strings.TrimSpace(userVal)
	intVal, err := strconv.Atoi(input)
	if err != nil {
		return err
	}

	fmt.Printf(&quot;You entered: %d\n&quot;, intVal)
	return nil
}

func main() {
	getInt()
}

答案7

得分: 0

为什么我们不能只使用scanf?就像在C语言中一样?尽管它是有效的。

package main
import "fmt"
func main() {
    var i int
    fmt.Scanf("%d", &i)
    fmt.Println(i)
}
英文:

Why can't we just use a scanf? just like we use in C? it's working though.

package main
import &quot;fmt&quot;
func main() {
	var i int
	fmt.Scanf(&quot;%d&quot;, &amp;i)
	fmt.Println(i)
}

huangapple
  • 本文由 发表于 2010年9月20日 20:22:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/3751429.html
匿名

发表评论

匿名网友

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

确定