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条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路