我正在开发一个应该读取文件内容并从中提取数据的程序。我尝试使用 fmt.Fscanf() 逐行扫描内容,但由于某种原因,我无法使其正常工作。整行仅被扫描到第一个字符串参数中。我在这里做错了什么?
我假设它不起作用,因为值没有用空格分隔,但我找不到解决方案。感谢您的帮助和专业知识!
20220105|AA|1051302|4323|3132468|B,Q,N
20220105|AAA|61|0|62|Q
20220105|AAAU|19404|0|57137|Q,N
20220105|AAC|35524|0|39861|Q,N
20220105|AAC/WS|1180|0|2000|N
20220105|AACG|1805439|32577|3484265|B,Q,N
func main() {
file, err := os.Open("./CNMSshvol20220105.txt")
if err != nil{
log.Fatal(err)
}
defer file.Close()
var m map[string][]int
m = make(map[string][]int)
for{
row := ""
date := ""
symbol := ""
shortVolume := 0
shortExemptVolume := 0
totalVolume := 0
markets := ""
//Date|Symbol|ShortVolume|ShortExemptVolume|TotalVolume|Market
var n int
n, err := fmt.Fscanf(file, "%s\n", &row)
fmt.Sscanf(row, "%s|%s|%d|%d|%d|%s", &date, &symbol, &shortVolume, &shortExemptVolume, &totalVolume,&markets)
fmt.Println(date)
if n == 0 || err != nil{
log.Fatalf("Fscanf: %v\n", err)
break
}
fmt.Println(symbol, shortVolume, shortExemptVolume, totalVolume)
m[strings.ToLower(symbol)] = append(m[strings.ToLower(symbol)],shortVolume)
m[strings.ToLower(symbol)] = append(m[strings.ToLower(symbol)],shortExemptVolume)
m[strings.ToLower(symbol)] = append(m[strings.ToLower(symbol)],totalVolume)
}
//Retrieve values if the key exists
for{
fmt.Println("\n\n\n\nEnter ticker to retrieve short volume information.")
var s string
fmt.Scanf("%s",&s)
data, ok := m[strings.ToLower(s)]
if !ok{
fmt.Println("Not Found.")
continue
}
for _, value := range data{
fmt.Println(value)
}
}
}```