• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang fmt.Sscanf函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中fmt.Sscanf函数的典型用法代码示例。如果您正苦于以下问题:Golang Sscanf函数的具体用法?Golang Sscanf怎么用?Golang Sscanf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Sscanf函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: parse

func (p *file) parse(name string) bool {
	var num uint64
	var tail string
	_, err := fmt.Sscanf(name, "%d.%s", &num, &tail)
	if err == nil {
		switch tail {
		case "log":
			p.t = TypeLog
		case "sst":
			p.t = TypeTable
		case "dbtmp":
			p.t = TypeTemp
		default:
			return false
		}
		p.num = num
		return true
	}
	n, _ := fmt.Sscanf(name, "MANIFEST-%d%s", &num, &tail)
	if n == 1 {
		p.t = TypeManifest
		p.num = num
		return true
	}

	return false
}
开发者ID:yufeng108,项目名称:goleveldb,代码行数:27,代码来源:file_desc.go


示例2: readCursorPosition

func (ttyfd TTY) readCursorPosition() (int, int) {
	ttyfd.write(READ_CURSOR_POSITION)
	var chr byte
	var nb []byte = make([]byte, 0)
	var x, y int

	chr, _, _ = ttyfd.Readchr()
	if chr != ESC_CHR {
		return 0, 0 // something failed !
	}
	chr, _, _ = ttyfd.Readchr()
	if chr != '[' {
		return 0, 0 // something failed !
	}

	for chr != ';' {
		chr, _, _ = ttyfd.Readchr()
		nb = append(nb, chr)
	}
	fmt.Sscanf(string(nb), "%d", &x)
	nb = make([]byte, 0)
	for chr != 'R' {
		chr, _, _ = ttyfd.Readchr()
		nb = append(nb, chr)
	}
	fmt.Sscanf(string(nb), "%d", &y)
	return x, y

}
开发者ID:gbin,项目名称:screencastinator,代码行数:29,代码来源:ui.go


示例3: Put

/*
The "put" command is for any process that wants to insert a job into the queue.
It comprises a command line followed by the job body:

put <pri> <delay> <ttr> <bytes>\r\n
<data>\r\n

It inserts a job into the client's currently used tube (see the "use" command
below).

 - <pri> is an integer < 2**32. Jobs with smaller priority values will be
   scheduled before jobs with larger priorities. The most urgent priority is 0;
   the least urgent priority is 4,294,967,295.

 - <delay> is an integer number of seconds to wait before putting the job in
   the ready queue. The job will be in the "delayed" state during this time.

 - <ttr> -- time to run -- is an integer number of seconds to allow a worker
   to run this job. This time is counted from the moment a worker reserves
   this job. If the worker does not delete, release, or bury the job within
   <ttr> seconds, the job will time out and the server will release the job.
   The minimum ttr is 1. If the client sends 0, the server will silently
   increase the ttr to 1.

 - <bytes> is an integer indicating the size of the job body, not including the
   trailing "\r\n". This value must be less than max-job-size (default: 2**16).

 - <data> is the job body -- a sequence of bytes of length <bytes> from the
   previous line.

After sending the command line and body, the client waits for a reply, which
may be:

 - "INSERTED <id>\r\n" to indicate success.

   - <id> is the integer id of the new job

 - "BURIED <id>\r\n" if the server ran out of memory trying to grow the
   priority queue data structure.

   - <id> is the integer id of the new job

 - "EXPECTED_CRLF\r\n" The job body must be followed by a CR-LF pair, that is,
   "\r\n". These two bytes are not counted in the job size given by the client
   in the put command line.

 - "JOB_TOO_BIG\r\n" The client has requested to put a job with a body larger
   than max-job-size bytes.

 - "DRAINING\r\n" This means that the server has been put into "drain mode"
   and is no longer accepting new jobs. The client should try another server
   or disconnect and try again later.
*/
func (this *BeanstalkdClient) Put(priority uint32, delay, ttr time.Duration, data []byte) (id uint64, err error) {
	cmd := fmt.Sprintf("put %d %d %d %d\r\n", priority, uint64(delay.Seconds()), uint64(ttr.Seconds()), len(data))
	cmd = cmd + string(data) + string(crnl)

	_, reply, err := this.sendReply(cmd)

	if err != nil {
		return 0, err
	}

	switch {
	case strings.Index(reply, "INSERTED") == 0:
		var id uint64
		_, perr := fmt.Sscanf(reply, "INSERTED %d\r\n", &id)
		return id, perr
	case strings.Index(reply, "BURIED") == 0:
		var id uint64
		_, perr := fmt.Sscanf(reply, "BURIED %d\r\n", &id)
		return id, perr
	case reply == "EXPECTED_CRLF\r\n":
		return 0, errExpectedCrlf
	case reply == "JOB_TOO_BIG\r\n":
		return 0, errJobTooBig
	case reply == "DRAINING\r\n":
		return 0, errDraining
	default:
		return 0, this.parseError(reply)
	}

}
开发者ID:mpdroog,项目名称:smtpw,代码行数:83,代码来源:client.go


示例4: BlockStorageFactory

func BlockStorageFactory(opts map[string]string) (res Storage, err error) {
	op := &BlockStorageOptions{"data", 2, 32, 32}
	var ok bool
	var tmp string

	if tmp, ok = opts["root"]; ok {
		op.Root = tmp
	}
	if tmp, ok = opts["split"]; ok {
		if _, err = fmt.Sscanf(tmp, "%d", op.Split); err != nil {
			return
		}
	}
	if tmp, ok = opts["max-files"]; ok {
		if _, err = fmt.Sscanf(tmp, "%d", op.MaxFiles); err != nil {
			return
		}
	}
	if tmp, ok = opts["pool"]; ok {
		if _, err = fmt.Sscanf(tmp, "%d", op.PoolSize); err != nil {
			return
		}
	}

	res = NewBlockStorage(op)
	return
}
开发者ID:pombredanne,项目名称:bar,代码行数:27,代码来源:block.go


示例5: MyParseCallback

// Example custom option callback
func MyParseCallback(spec *options.OptionSpec, option string, argument *string) {
	if argument != nil {
		switch spec.GetCanonical(option) {
		case "input-encoding":
			in = *argument
		case "output-encoding":
			out = *argument
		case "repeat":
			fmt.Sscanf(*argument, "%d", &r)
		case "cookie-chance":
			fmt.Sscanf(*argument, "%f", &c)
			cInt = int64(c * 1000)
		default:
			spec.PrintUsageAndExit("Unknown option: " + option)
		}
	} else {
		switch spec.GetCanonical(option) {
		case "number":
			n = true
		case "escape":
			e = true
		case "verbose":
			v++
		default:
			if option == "help" {
				spec.PrintUsageAndExit("") // No error
			} else {
				spec.PrintUsageAndExit("Unknown option: " + option)
			}
		}
	}
}
开发者ID:elasticdog,项目名称:go-options,代码行数:33,代码来源:cat2.go


示例6: ParseRelease

func ParseRelease(release string) (*KernelVersionInfo, error) {
	var (
		kernel, major, minor, parsed int
		flavor, partial              string
	)

	// Ignore error from Sscanf to allow an empty flavor.  Instead, just
	// make sure we got all the version numbers.
	parsed, _ = fmt.Sscanf(release, "%d.%d%s", &kernel, &major, &partial)
	if parsed < 2 {
		return nil, errors.New("Can't parse kernel version " + release)
	}

	// sometimes we have 3.12.25-gentoo, but sometimes we just have 3.12-1-amd64
	parsed, _ = fmt.Sscanf(partial, ".%d%s", &minor, &flavor)
	if parsed < 1 {
		flavor = partial
	}

	return &KernelVersionInfo{
		Kernel: kernel,
		Major:  major,
		Minor:  minor,
		Flavor: flavor,
	}, nil
}
开发者ID:GloriaH,项目名称:docker,代码行数:26,代码来源:utils.go


示例7: LoadString

// LoadString loads a hex representation (including checksum) of an unlock hash
// into an unlock hash object. An error is returned if the string is invalid or
// fails the checksum.
func (uh *UnlockHash) LoadString(strUH string) error {
	// Check the length of strUH.
	if len(strUH) != crypto.HashSize*2+UnlockHashChecksumSize*2 {
		return ErrUnlockHashWrongLen
	}

	// Decode the unlock hash.
	var byteUnlockHash []byte
	var checksum []byte
	_, err := fmt.Sscanf(strUH[:crypto.HashSize*2], "%x", &byteUnlockHash)
	if err != nil {
		return err
	}

	// Decode and verify the checksum.
	_, err = fmt.Sscanf(strUH[crypto.HashSize*2:], "%x", &checksum)
	if err != nil {
		return err
	}
	expectedChecksum := crypto.HashBytes(byteUnlockHash)
	if !bytes.Equal(expectedChecksum[:UnlockHashChecksumSize], checksum) {
		return ErrInvalidUnlockHashChecksum
	}

	copy(uh[:], byteUnlockHash[:])
	return nil
}
开发者ID:robvanmieghem,项目名称:Sia,代码行数:30,代码来源:unlockhash.go


示例8: main

func main() {
	data, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer data.Close()

	var (
		n, id  int
		x, y   float64
		places []place
		path   []int
	)
	scanner := bufio.NewScanner(data)
	for scanner.Scan() {
		t := strings.Fields(scanner.Text())
		fmt.Sscan(t[0], &id)
		fmt.Sscanf(t[len(t)-2], "(%f,", &x)
		fmt.Sscanf(t[len(t)-1], "%f)", &y)
		places = append(places, place{id, x, y})
		path = append(path, n)
		n++
	}
	shortestPath, _ := findPath(path, []int{}, 0, tour(places, path), len(path), places)
	for _, i := range shortestPath {
		fmt.Println(places[i].id)
	}
}
开发者ID:nikai3d,项目名称:ce-challenges,代码行数:28,代码来源:commuting_engineer.go


示例9: main

func main() {

	var n int
	fmt.Scanf("%d\n", &n)
	re := regexp.MustCompile("(R\\d+C\\d+)|(([A-Z]+)(\\d+))")

	for i := 0; i < n; i++ {

		var k string
		fmt.Scanf("%s\n", &k)

		ss := re.FindStringSubmatch(k)

		if len(ss[1]) > 0 {
			var a, b int
			fmt.Sscanf(ss[1], "R%dC%d", &a, &b)
			fmt.Printf("%s%d\n", itos(b), a)
		}

		if len(ss[2]) > 0 {
			a := ss[3]
			var b int
			fmt.Sscanf(ss[4], "%d", &b)
			fmt.Printf("R%dC%d\n", b, stoi(a))
		}
	}

}
开发者ID:giter,项目名称:codeforces-ans,代码行数:28,代码来源:1B.go


示例10: main

func main() {
	cgreader.RunStaticPrograms(
		cgreader.GetFileList("../../input/horse_dual_%d.txt", 3),
		cgreader.GetFileList("../../output/horse_dual_%d.txt", 3),
		true,
		func(input <-chan string, output chan string) {
			var n int
			fmt.Sscanf(<-input, "%d", &n)

			horses := make([]int, n)
			for i := range horses {
				fmt.Sscanf(<-input, "%d", &horses[i])
			}

			sort.Sort(intArray(horses))

			D := math.MaxInt32
			for i := 1; i < n; i++ {
				x := horses[i-1] - horses[i]

				if x < 0 {
					x *= -1
				}

				if x < D {
					D = x
				}
			}

			output <- fmt.Sprintf("%d", D)
		})
}
开发者ID:shawshining,项目名称:Codingame,代码行数:32,代码来源:horse_dual.go


示例11: ParseKeyEvent

func ParseKeyEvent(arg string) (*KeyEvent, error) {
	var key string
	var down bool

	_, err := fmt.Sscanf(arg, _KeyEventFmt, &down, &key)
	if err != nil {
		return nil, err
	}

	m := &KeyEvent{}

	m.Key, err = xStringToKeysym(key)
	if err != nil {
		fmt.Println(err.Error())
		_, err = fmt.Sscanf(key, "%U", &m.Key)
		if err != nil {
			fmt.Println(err.Error())
			return nil, fmt.Errorf("unknown key: `%s`", key)
		}
	}

	if down {
		m.DownFlag = 1
	}

	return m, nil
}
开发者ID:cdshann,项目名称:minimega,代码行数:27,代码来源:client.go


示例12: IntBytes

func IntBytes(arg string) (bool, int, []byte) {
	if !BytesRE.MatchString(arg) {
		return false, -1, nil
	}

	r := make([]byte, 0)

	for _, segment := range strings.Split(arg, " ", -1) {
		var n byte

		switch len(segment) {
		case 2:
			_, err := fmt.Sscanf(segment, "%x", &n)
			if err != nil {
				return false, -1, nil
			}
			r = append(r, n)
		case 4:
			_, err := fmt.Sscanf(segment[0:2], "%x", &n)
			if err != nil {
				return false, -1, nil
			}
			r = append(r, n)
			_, err = fmt.Sscanf(segment[2:], "%x", &n)
			if err != nil {
				return false, -1, nil
			}
			r = append(r, n)
		default:
			return false, -1, nil
		}
	}

	return true, -1, r
}
开发者ID:aarzilli,项目名称:chade,代码行数:35,代码来源:interpreters.go


示例13: lsusb

func lsusb(path string) error {
	f, err := os.Open(path)
	if err != nil {
		return nil
	}
	defer f.Close()

	var bus, dev, pid, vid, i int
	s := bufio.NewScanner(f)
	for s.Scan() {
		line := s.Text()
		n1, _ := fmt.Sscanf(line, "BUSNUM=%d\n", &bus)
		n2, _ := fmt.Sscanf(line, "DEVNUM=%d\n", &dev)
		n3, _ := fmt.Sscanf(line, "PRODUCT=%x/%x\n", &pid, &vid)
		if n1 != 0 || n2 != 0 || n3 != 0 {
			i++
		}
		if i == 3 {
			devices = append(devices, Device{bus, dev, pid, vid})
			break
		}
	}

	return nil
}
开发者ID:qeedquan,项目名称:misc_utilities,代码行数:25,代码来源:lsusb.go


示例14: WatchdogEnabled

// WatchdogEnabled checks whether the service manager expects watchdog keep-alive notifications and
// returns the timeout value in µs. A timeout value of 0 signifies no notifications are expected.
func WatchdogEnabled() (time.Duration, error) {
	spid := os.Getenv("WATCHDOG_PID")
	if spid != "" {
		pid := 0
		n, err := fmt.Sscanf(spid, "%d", &pid)
		if err != nil {
			return 0, err
		}
		if n != 1 {
			return 0, errors.New("could not scan WATCHDOG_PID")
		}
		if pid != os.Getpid() {
			return 0, nil
		}
	}

	sttl := os.Getenv("WATCHDOG_USEC")
	if sttl == "" {
		return 0, errors.New("missing WATCHDOG_USEC")
	}
	ttl := uint64(0)
	n, err := fmt.Sscanf(sttl, "%d", &ttl)
	if err != nil {
		return 0, err
	}
	if n != 1 {
		return 0, errors.New("could not scan WATCHDOG_USEC")
	}
	return time.Duration(ttl) * time.Microsecond, nil
}
开发者ID:joshie,项目名称:lochness,代码行数:32,代码来源:sd_watchdog_enabled.go


示例15: stringRangeWorker

func stringRangeWorker(rangeRepr string, ch chan int) {
	for _, part := range strings.Split(rangeRepr, ",") {
		var from, to int
		var err error

		data := []byte(part)
		if match := numberRe.FindSubmatch(data); match != nil {
			fmt.Sscanf(string(match[1]), "%d", &from)
			to = from
		} else if match := rangeRe.FindSubmatch(data); match != nil {
			fmt.Sscanf(string(match[1]), "%d", &from)
			fmt.Sscanf(string(match[2]), "%d", &to)
		} else {
			break
		}

		if err != nil {
			break
		}

		for i := from; i <= to; i++ {
			ch <- i
		}
	}
	close(ch)
}
开发者ID:lanior,项目名称:upc,代码行数:26,代码来源:import.go


示例16: ParseGameState

func ParseGameState(lines []string) *PlanetWars {
	pw := &PlanetWars{make([]*Planet, len(lines)), make([]*Fleet, len(lines))}
	pNum, fNum := 0, 0

	for _, ln := range lines {

		switch ln[0] {
		case 'P':
			p := &Planet{ID: pNum}
			read, e := fmt.Sscanf(ln[2:], "%f %f %d %d %d", &p.X, &p.Y, &p.Owner, &p.NumShips, &p.GrowthRate)

			if read < 5 || e != nil {
				log.Stderrf("Bad line in input: %s\n", ln)
			}
			pw.Planets[pNum] = p
			pNum++
		case 'F':
			f := &Fleet{ID: fNum}
			read, e := fmt.Sscanf(ln[2:], "%d %d %d %d %d", &f.Owner, &f.NumShips, &f.Source, &f.Dest, &f.TripLength, &f.TurnsRemaining)

			if read < 5 || e != nil {
				log.Stderrf("Bad line in input: %s\n", ln)
			}
			pw.Fleets[fNum] = f
			fNum++
		default:
			log.Stderr("Error parsing gamestate: First char of line not 'P' or 'F'\n")
			return nil
		}
	}

	pw.Fleets = pw.Fleets[0:fNum]
	pw.Planets = pw.Planets[0:pNum]
	return pw
}
开发者ID:vil1,项目名称:ai-contest,代码行数:35,代码来源:PlanetWars.go


示例17: main

func main() {
	cgreader.RunStaticPrograms(
		cgreader.GetFileList("../../input/tan_network_%d.txt", 6),
		cgreader.GetFileList("../../output/tan_network_%d.txt", 6),
		true,
		func(input <-chan string, output chan string) {
			// this block could be ommited when solo-running
			minCost = math.MaxUint16
			routes, finalRoute = nil, nil

			start, stop := GetInput(input), GetInput(input)
			hashMap = make(map[uint32]string)
			identifierMap = make(map[string]uint32)
			stationsMC = make(map[uint32]uint16)

			var ns, nr uint32
			fmt.Sscanf(<-input, "%d", &ns)
			stations := make(map[uint32]Station)
			for i := uint32(0); i < ns; i++ {
				station := GetInput(input)
				info := strings.Split(station, ",")
				hashMap[i] = info[0]
				identifierMap[info[0]] = i
				stations[i] = Station{
					info[1][1 : len(info[1])-1],
					ToFloat(info[3]),
					ToFloat(info[4])}
			}

			startHash, finalHash = identifierMap[start], identifierMap[stop]

			if startHash == finalHash {
				output <- stations[startHash].name
				return
			}

			fmt.Sscanf(<-input, "%d", &nr)
			routes = make(map[uint32][]Destination)
			for i := uint32(0); i < nr; i++ {
				route := GetInput(input)
				ra, ro := string(route[:4]), string(route[14:])
				ha, ho := identifierMap[ra], identifierMap[ro]

				a, b := stations[ha], stations[ho]
				cost := GetCost(a.latitude, b.latitude, a.longitude, b.longitude)

				routes[ha] = append(routes[ha], Destination{ho, cost})
			}

			TravelRecursive(0, append(make([]uint32, 0), startHash))

			if finalRoute == nil {
				output <- "IMPOSSIBLE\n"
			} else {
				for _, hash := range finalRoute {
					output <- fmt.Sprintln(stations[hash].name)
				}
			}
		})
}
开发者ID:shawshining,项目名称:Codingame,代码行数:60,代码来源:tan_network.go


示例18: formatCompleteOutput

// formatCompleteOutput will format the message m as an completed message.
func formatCompleteOutput(m *jsonmessage.JSONMessage) string {
	if strings.HasPrefix(m.Status, "The push refers to a repository") {
		return "Pushing to registry"
	}

	if strings.HasPrefix(m.Status, "Pushing repository") &&
		strings.HasSuffix(m.Status, "tags)") {
		tags := 0
		registry := ""
		fmt.Sscanf(m.Status, "Pushing repository %s (%d tags)", &registry, &tags)
		return fmt.Sprintf("Pushing %d tag(s)", tags)
	}

	if strings.HasPrefix(m.Status, "Pushing tag for rev [") &&
		strings.HasSuffix(m.Status, "};") {
		image := ""
		registry := ""
		fmt.Sscanf(m.Status, "Pushing tag for rev [%s] on {%s};", &image, &registry)
		image = strings.TrimSuffix(image, "]")
		return fmt.Sprintf("Pushing tag for image: %s", image)
	}

	if m.ID != "" {
		return fmt.Sprintf("%s: %s", m.Status, m.ID)
	}

	return m.Status
}
开发者ID:wercker,项目名称:wercker,代码行数:29,代码来源:status_handler.go


示例19: main

func main() {
	data, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer data.Close()
	scanner := bufio.NewScanner(data)
	for scanner.Scan() {
		s := strings.Split(scanner.Text(), ",")
		var l, m int
		fmt.Sscanf(strings.TrimSpace(s[0]), "%d", &m)
		for _, i := range s {
			var v int
			fmt.Sscanf(strings.TrimSpace(i), "%d", &v)
			if v > m {
				m = v
			}
			if v+l > m {
				m = v + l
			}
			if v+l > 0 {
				l += v
			} else {
				l = 0
			}
		}
		fmt.Println(m)
	}
}
开发者ID:oorja,项目名称:ce-challenges,代码行数:29,代码来源:largest_sum.go


示例20: placepic

// placepic puts a SVG file at a location
func placepic(x, y int, filename string) (int, int) {
	var (
		s             SVG
		width, height int
		wunit, hunit  string
	)
	f, err := os.Open(filename)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return 0, 0
	}
	defer f.Close()
	if err := xml.NewDecoder(f).Decode(&s); err != nil {
		fmt.Fprintf(os.Stderr, "Unable to parse (%v)\n", err)
		return 0, 0
	}

	// read the width and height, including any units
	// if there are errors use 10 as a default
	nw, _ := fmt.Sscanf(s.Width, "%d%s", &width, &wunit)
	if nw < 1 {
		width = 10
	}
	nh, _ := fmt.Sscanf(s.Height, "%d%s", &height, &hunit)
	if nh < 1 {
		height = 10
	}
	canvas.Group(`clip-path="url(#pic)"`, fmt.Sprintf(`transform="translate(%d,%d)"`, x, y))
	canvas.ClipPath(`id="pic"`)
	canvas.Rect(0, 0, width, height)
	canvas.ClipEnd()
	io.WriteString(canvas.Writer, s.Doc)
	canvas.Gend()
	return width, height
}
开发者ID:sara62,项目名称:centrifugo,代码行数:36,代码来源:svgrid.go



注:本文中的fmt.Sscanf函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang fmt.Sscanln函数代码示例发布时间:2022-05-24
下一篇:
Golang fmt.Sscan函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap