从标准输入读取整数

发布于 2024-09-24 03:36:43 字数 117 浏览 4 评论 0原文

如何使用 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

初心 2024-10-01 03:36:43

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

淡淡绿茶香 2024-10-01 03:36:43

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

package main

import "fmt"

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

这使用参数类型的反射来发现应如何解析输入。

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

青春有你 2024-10-01 03:36:43

这是我读取正整数的“快速 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 {
    //assumes POSITIVE INTEGERS. Check v for '-' 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 '0' <= v && v <= '9' {
            num = 10*num + int64(v - '0') //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
}

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 (
    "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 {
    //assumes POSITIVE INTEGERS. Check v for '-' 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 '0' <= v && v <= '9' {
            num = 10*num + int64(v - '0') //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
}
梦境 2024-10-01 03:36:43

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

如果 fmt.Scan 错误,即如果不是 nil,则 log & return

1 读取单个变量:

import (
    "fmt"
    "log"
)

var i int
if    _, err := fmt.Scan(&i);    err != nil {
    log.Print("  Scan for i failed, due to ", 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("  Scan for i, j & k failed, due to ", 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 (
    "fmt"
    "log"
)

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

fmt.Println(i)

2 Read multiple variables:

import (
    "fmt"
    "log"
)

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

fmt.Println(i, j, k)

Best of luck

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

宁愿没拥抱 2024-10-01 03:36:43

您可以将 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("%d", &someVar)
}

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

func main() {
   var someVar int
   fmt.Scanln(&someVar)
}
很糊涂小朋友 2024-10-01 03:36:43

您还可以使用 bufio.NewReader 从标准输入读取整数。

以下程序:

  • 提示输入整数

  • 创建 bufio.Reader 以从标准输入读取

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

  • 删除换行符字符

  • 将字符串转换为int

package main

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

func getInt() error {
    fmt.Println("Enter an integer")
    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("You entered: %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 '\n' (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 (
    "fmt"
    "bufio"
    "os"
    "strconv"
    "strings"
)

func getInt() error {
    fmt.Println("Enter an integer")
    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("You entered: %d\n", intVal)
    return nil
}

func main() {
    getInt()
}
毁虫ゝ 2024-10-01 03:36:43

为什么我们不能只使用 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 "fmt"
func main() {
    var i int
    fmt.Scanf("%d", &i)
    fmt.Println(i)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文