So far, I haven't been able to print a rune by scanning it with fmt.Scan
and printing it with fmt.Print
. This is the vary basic code I'm working on:
package main
import "fmt"
func main() {
var c rune
fmt.Scan(&c)
fmt.Printf("%c", c)
}
But it doesn't work, in fact, Printf
doesn't produce any output. Instead, by manually assigning a char to my variable c (like var c rune = 'a'
, without using fmt.Scan
), I'm able to print the wanted rune. How can I scan a rune?
CodePudding user response:
here are two methods:
package fmt
import (
"fmt"
"strings"
)
func scan_fmt(s string) (rune, error) {
var c rune
_, err := fmt.Sscanf(s, "%c", &c)
if err != nil {
return 0, err
}
return c, nil
}
func scan(s string) (rune, error) {
c, _, err := strings.NewReader(s).ReadRune()
if err != nil {
return 0, err
}
return c, nil
}
https://godocs.io/strings#Reader.ReadRune
CodePudding user response:
As we know Scan
return n and err so please check for error under Scan
statement as follows
n, err := fmt.Scan(&c)
if err != nil {
fmt.Println(err)
}
It will clearly show you the error and why it was ignored.
Other than the above, please try it locally on your own laptop instead of the playground because on the playground it most of the time gives an EOF
error as most of them do not support reading from the terminal.
I hope the above helps you in debugging the issue.
Other Reference: