duan01203 2012-03-03 17:21
浏览 65
已采纳

哪个扫描用于读取字符串的浮点数?

This seems almost right but it chokes on the newline. What's the best way to do this?

package main

import (
    "fmt"
    "strings"
)

func main() {
    var z float64
    var a []float64
    // 
 gives an error for Fscanf
    s := "3.25 -12.6 33.7 
 3.47"
    in := strings.NewReader(s)
    for {
        n, err := fmt.Fscanf(in, "%f", &z)
        fmt.Println("n", n)
        if err != nil {
            break
        }
        a = append(a, z)
    }
    fmt.Println(a)
}

Output:

n 1
n 1
n 1
n 0
[3.25 -12.6 33.7]

Update:

See the answer from @Atom below. I found another way which is to break if the error is EOF, and otherwise just ignore it. It's just a hack, I know, but I control the source.

    _, err := fmt.Fscanf(in, "%f", &z)
    if err == os.EOF { break }
    if err != nil { continue }
  • 写回答

2条回答 默认 最新

  • drtkyykai004574380 2012-03-03 19:07
    关注

    If you are parsing floats only, you can use fmt.Fscan(r io.Reader, a ...interface{}) instead of fmt.Fscanf(r io.Reader, format string, a ...interface{}):

    var z float64
    ...
    n, err := fmt.Fscan(in, &z)
    

    The difference between fmt.Fscan and fmt.Fscanf is that in the case of fmt.Fscan newlines count as space. The latter function (with a format string) does not treat newlines as spaces and requires newlines in the input to match newlines in the format string.

    The functions with a format string give more control over the form of input, such as when you need to scan %5f or %10s. In this case, if the input contains newlines and it implements the interface io.RuneScanner you can use the method ReadRune to peek the next character and optionally unread it with UnreadRune if it isn't a space or a newline.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退