fmt.Sscanf documentation says: Sscanf scans the argument string, storing successive space-separated values into successive arguments as determined by the format

| character is not space and each format placeholder is independent of any other, so %s| does not mean match any string up to a first | but instead match any string not including space, and then a |.

You can process file line by line, split each line e.g using strings.Split() by | and then parse values into variables as you need:

row := "20220105|AACG|1805439|32577|3484265|B,Q,N"
tokens := strings.Split(row, "|")
if len(tokens) != 6 {
    log.Fatal("Bad line in file...")
}

// Do appropriate conversions...
date, err := strconv.Atoi(tokens[0])
if err != nil {
    log.Fatal("first token is not an integer")
}
symbol := tokens[1]
// ...

fmt.Println(date, symbol)

or as Volker pointed out in his comment you can use package encoding/csv and set its Reader Comma (separator) option to |:

f := `20220105|AA|1051302|4323|3132468|B,Q,N
20220105|AAA|61|0|62|Q`

r := csv.NewReader(strings.NewReader(f))
r.Comma = '|'
data, err := r.ReadAll()
if err != nil {
    log.Fatal(err)
}

// Process data, do appropriate conversions

fmt.Print(data)
Answer from blami on Stack Overflow
🌐
Go Packages
pkg.go.dev › fmt
fmt package - fmt - Go Packages
An analogous set of functions scans formatted text to yield values. Scan, Scanf and Scanln read from os.Stdin; Fscan, Fscanf and Fscanln read from a specified io.Reader; Sscan, Sscanf and Sscanln read from an argument string.
🌐
Reddit
reddit.com › r/golang › i am bit confused about golang’s scanf
r/golang on Reddit: I am bit confused about golang’s scanf
December 16, 2020 -

Hi! With the occasion of this year’s adventofcode i decided to learn golang because it looked really cool. Today i had to parse some input which was of the following format: string: int-int or int-int For example

Departure time: 10-20 or 22-23

I read the text file line by line and tried the following

fmt.Sscanf(scanner.Text(),“%s: %d-%d or %d-%d,...);

This said that the input string doesnt match the format After that I’ve tried

fmt.Sscanf(scanner.Text(),“%s %d-%d or %d-%d,...);

This didnt panic but read the whole line into the first string. After that I’ve tried separating the string i needed and just parse the sequence of ints So i wrote

fmt.Sscanf(numbers_only,”%d-%d or %d-%d”,...)

This again said that the input doesn’t match the format. Any idea what I did wrong, or if indeed golang doesnt work perfectly with scanf? From my experience with c/c++, I know that doing the exact same thing there would work, but i cant figure out why it doesnt in golang.

Discussions

go - Golang: How do I use fmt.Fscanf() & fmt.Sscanf() correctly? - Stack Overflow
I'm working on a program that is supposed to read the contents of a file and extract the data from it. I've tried to use fmt.Fscanf() to scan the contents line by line, but for some reason, I can't... More on stackoverflow.com
🌐 stackoverflow.com
fmt: confusion about Scanf patterns, newline, space
While updating code using fmt.Scanf after CL 16165, I discovered that there were users with patterns ending in \n as a way to assert that Scanf had consumed an entire input. The examples that follo... More on github.com
🌐 github.com
13
December 10, 2015
go - Sscanf of multiple string fields in golang - Stack Overflow
I am trying to use sscanf to parse multiple string fields. More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
fmt: Scanf / Sscanf does not properly treat carriage return symbol, behaves different with C function
We simply try reading with fmt.Sscanf (from the prepared string, but it is the same with fmt.Scanf reading from stdin - just more difficult to demonstrate) - there are two integer values, separated with windows-style newline (\r\n). More on github.com
🌐 github.com
1
August 28, 2024
🌐
Educative
educative.io › answers › what-is-the-golang-sscanf-function
What is the golang Sscanf function?
In the Go programming language, the Sscanf function is used to read data from a source string of your choosing, format it into a string, and store the resultant space-separated strings into the destinations specified by a list of additional ...
🌐
GeeksforGeeks
geeksforgeeks.org › go language › fmt-sscanf-function-in-golang-with-examples
fmt.Sscanf() Function in Golang With Examples - GeeksforGeeks
May 5, 2020 - // Golang program to illustrate the usage of // fmt.Sscanf() function // Including the main package package main // Importing fmt import ( "fmt" ) // Calling main func main() { // Declaring some variables var name string var alphabet_count int var float_value float32 var boolean_value bool // Calling the Sscanf() function which // returns the number of elements // successfully parsed and error if // it persists n, err := fmt.Sscanf("GeeksforGeeks 13 6.7 true", "%s %d %g %t", &name, &alphabet_count, &float_value, &boolean_value) // Below statements get executed // if there is any error if err != nil { panic(err) } // Printing the number of elements // and each elements also fmt.Printf("%d: %s, %d, %g, %t", n, name, alphabet_count, float_value, boolean_value) } Output:
🌐
Google Groups
groups.google.com › g › golang-nuts › c › dq4nykzR5n8
fmt.Sscanf strange behaviour
to Victor Giordano, golang-nuts · Using %s in fmt.Sscanf will read all characters up to a space or newline.
🌐
GitHub
github.com › golang › go › issues › 13565
fmt: confusion about Scanf patterns, newline, space · Issue #13565 · golang/go
December 10, 2015 - # Go 1.5 fmt.Sscanf("1 2", "%d %d\n", &x, &y) 2 <nil> 1 2 fmt.Sscanf("1 2 3", "%d %d\n", &x, &y) 2 newline in format does not match input 1 2
Author   rsc
🌐
IncludeHelp
includehelp.com › golang › fmt-sscanf-function-with-examples.aspx
Golang fmt.Sscanf() Function with Examples
October 10, 2021 - The return type of the fmt.Sscanf() function is a string, it returns the number of total items successfully parsed and an error if occurred during paring. ... // Golang program to demonstrate the // example of fmt.Sscanf() function package main import ( "fmt" ) func main() { var x int var y int // Scans the values (space-separated) // and assigns to the variables fmt.Sscanf("10 20", "%d %d", &x, &y) // Prints the values fmt.Println("x:", x) fmt.Println("y:", y) // Scans the values (newline-separated) // and assigns to the variables fmt.Sscanf("30\n40", "%d\n%d", &x, &y) // Prints the values fmt.Println("x:", x) fmt.Println("y:", y) // Scans the values (Tab-separated) // and assigns to the variables fmt.Sscanf("50\t60", "%d\t%d", &x, &y) // Prints the values fmt.Println("x:", x) fmt.Println("y:", y) }
Find elsewhere
🌐
Chris's Wiki
utcc.utoronto.ca › ~cks › space › blog › programming › GoSscanfTrailingText
Trailing text, a subtle gotcha with Go's fmt.Sscanf
December 8, 2016 - You're probably reading this page because you've attempted to access some part of my blog (Wandering Thoughts) or CSpace, the wiki thing it's part of. Unfortunately you're using a browser (or client library) that my anti-crawler precautions consider suspicious because it's sending inconsistent ...
🌐
Dot Net Perls
dotnetperls.com › sscan-go
Go - fmt.Sscan, Sscanf Examples - Dot Net Perls
0 // Use format string to parse in values. // ... We parse 1 number, 1 string and 1 number. _, err := fmt.Sscanf("10 Bird 5", "%d %s %d", &value1, &value2, &value3); if err == nil { fmt.Println("VALUE1:", value1); fmt.Println("VALUE2:", value2); fmt.Println("VALUE3:", value3); } }
🌐
GitHub
github.com › golang › go › blob › master › src › fmt › scan.go
go/src/fmt/scan.go at master · golang/go
// Sscanf scans the argument string, storing successive space-separated · // values into successive arguments as determined by the format. It · // returns the number of items successfully parsed.
Author   golang
🌐
IncludeHelp
includehelp.com › golang › demonstrate-the-fmt-sscanf-function.aspx
Golang program to demonstrate the fmt.Sscanf() function
April 19, 2021 - The source code to demonstrate the fmt.Sscanf() function is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully. // Golang program to demonstrate the // fmt.Sscanf() function package main import "fmt" func main() { var dd int = 0 var mm int = 0 var yy int = 0 var strDate string = "17-04-20" _, err := fmt.Sscanf(strDate, "d-d-d", &dd, &mm, &yy) if err != nil { panic(err) } fmt.Println("DD: ", dd) fmt.Println("MM: ", mm) fmt.Println("YY: ", yy) }
🌐
GeeksforGeeks
geeksforgeeks.org › fmt-scanf-function-in-golang-with-examples
fmt.Scanf() Function in Golang With Examples - GeeksforGeeks
April 28, 2025 - The fmt.Sscanf() function in Go language scans the specified string and stores the successive space-separated values into successive arguments as determined by the format. Moreover, th · 2 min read · fmt.Sscan() Function in Golang With Examples ·
🌐
ZetCode
zetcode.com › golang › fmt-sscanf
Understanding the fmt.Sscanf Function in Golang
May 8, 2025 - In Go, fmt.Sscanf provides formatted scanning from strings similar to C's sscanf. It returns the number of items successfully parsed.
🌐
Reddit
reddit.com › r/golang › alternatives to scanf?
r/golang on Reddit: Alternatives to scanf?
March 21, 2019 -

I've been teaching myself competitive programming using Go (yes, I'm aware it's a better idea to do it with c++, but I currently work in Go and intend to interview with it).

I came across a post saying avoid Scanf - is the entire family slow or just Scanf specifically?

What would you use in place of fmt.Sscanf(str, "%s%d%s%d", ...)? a for loop and strconv?

🌐
7-Zip Documentation
documentation.help › Golang › fmt.htm
fmt - The Go Programming Language - Golang Documentation
Sscanf scans the argument string, storing successive space-separated values into successive arguments as determined by the format.
🌐
Go Forum
forum.golangbridge.org › getting help
Beginners on fmt.SScanf (possible bug?) - Getting Help - Go Forum
July 27, 2018 - I’m trying to parse “1.3p” as “%f%c” with fmt.Sscanf and always get 0.0 for the float. Is this a bug? Check at https://play.golang.org/p/2bEdp4PlaGe
Top answer
1 of 3
4

Your updated code was much easier to compile without the line numbers, but it was missing the package and import statements.

Looking at your code, I noticed a few things. Here's my revised version of your code.

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "strconv"
    "strings"
    "container/vector"
)

func main() {
    n := scanf(os.Stdin)
    fmt.Println()
    fmt.Println(len(n), n)
}

func scanf(in io.Reader) []int {
    var nums vector.IntVector
    rd := bufio.NewReader(os.Stdin)
    str, err := rd.ReadString('\n')
    for err != os.EOF {
        fields := strings.Fields(str)
        for _, f := range fields {
            if i, err := strconv.Atoi(f); err == nil {
                nums.Push(i)
            }
        }
        str, err = rd.ReadString('\n')
    }
    return nums
}

I might want to use any input file for scanf(), not just Stdin; scanf() takes an io.Reader as a parameter.

You wrote: nums := new(vector.IntVector), where type IntVector []int. This allocates an integer slice reference named nums and initializes it to zero, then the new() function allocates an integer slice reference and initializes it to zero, and then assigns it to nums. I wrote: var nums vector.IntVector, which avoids the redundancy by simply allocating an integer slice reference named nums and initializing it to zero.

You didn't check the err value for strconv.Atoi(), which meant invalid input was converted to a zero value; I skip it.

To copy from the vector to a new slice and return the slice, you wrote:

r := make([]int, nums.Len())
for i := 0; i < nums.Len(); i++ {
    r[i] = nums.At(i)
}
return r

First, I simply replaced that with an equivalent, the IntVector.Data() method: return nums.Data(). Then, I took advantage of the fact that type IntVector []int and avoided the allocation and copy by replacing that by: return nums.

2 of 3
0

This example always reads in a line at a time and returns the entire line as a string. If you want to parse out specific values from it you could.

package main

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

func main() {
    value :=    Input("Please enter a value: ")
    trimmed := strings.TrimSpace(value)
    fmt.Printf("Hello %s!\n", trimmed)
}

func Input(str string) string { 
        print(str) 
        reader := bufio.NewReader(os.Stdin) 
        input, _ := reader.ReadString('\n') 
        return input 
}