扫描精确数量的字符

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

scanning precise number of characters

问题

下面的代码打印出15,因为它最多扫描输入中的2个字符。如果它不能成功扫描恰好2个字符,是否可能使其失败?

package main

import (
	"errors"
	"fmt"
	"log"
)

func main() {
	var v uint8
	n, e := fmt.Sscanf("f!", "%02x", &v)
	if e != nil {
		log.Fatal(e)
	}
	if n != 1 {
		log.Fatal(errors.New("error"))
	}
	fmt.Println(v)
}

链接:https://play.golang.org/p/Wl3QyjS8YS

英文:

The code below prints 15 because it scans at most 2 characters in the input. Is it possible to make it fail if it does not scan successfully exactly 2 characters?

package main

import (
	"errors"
	"fmt"
	"log"
)

func main() {
	var v uint8
    n, e := fmt.Sscanf("f!", "%02x", &v)
	if e != nil {
		log.Fatal(e)
	}
	if n != 1 {
    	log.Fatal(errors.New("error"))
	}
    fmt.Println(v)
}

https://play.golang.org/p/Wl3QyjS8YS

答案1

得分: 0

我认为使用fmt.Sscanf无法完成这个任务。

但是使用strconv呢?

以下是一个示例:

package main

import (
	"strconv"
	"fmt"
)

// parse 从字符串 s 中以 16 进制的 base 解析出一个长度为 size 的 uint8 值
func parse(s string, size int) (uint8, error) {
	if len(s) != size {
		return 0, strconv.ErrSyntax
	}
	n, err := strconv.ParseUint(s, 16, 8)
	return uint8(n), err
}

func main() {
	for _, x := range []string{"ff", "f", "", "f!", "12", "00", "fff"} {
		if v, e := parse(x, 2); e == nil {
			fmt.Println("ok:", v)
		} else {
			fmt.Println("ko:", e)
		}
	}
}

在 playground 上查看:https://play.golang.org/p/PRkX0Wztz7

英文:

I think it cannot be done with fmt.Sscanf.

But what about using strconv instead?

Here is an example:

package main

import (
    "strconv"
    "fmt"
)

// parse reads a uint8 from s on exactly size digits in base 16
func parse( s string, size int ) (uint8, error) {
    if len(s) != size {
	    return 0, strconv.ErrSyntax
    }
    n,err := strconv.ParseUint(s,16,8)
    return uint8(n),err
}

func main() {
    for _,x := range []string{ "ff", "f", "", "f!", "12", "00", "fff" } {
	    if v,e := parse(x,2); e == nil {
		    fmt.Println("ok:",v)
	    } else {
		    fmt.Println("ko:",e)
	    }
    }	
}

In playground: https://play.golang.org/p/PRkX0Wztz7

huangapple
  • 本文由 发表于 2015年1月10日 23:45:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/27878003.html
匿名

发表评论

匿名网友

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

确定