Reputation: 21
I'm new at Go. I know it has some scanning functions: scan, sscan, scanf, sscanf and others.
but all of them, and I quote : "storing successive space-separated values", some treat new lines as spaces. but this is not I need.
I've already tried this:
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
fmt.Printf("Input Char Is : %v", string([]byte(input)[0]))
but this stops after new line not EOF.
I need a way to scan single chars one at a time until EOF. in C I would write:
while (getChar()){
//do stuff
}
What is the equivalent to this in Go?
Upvotes: 2
Views: 807
Reputation: 42959
Two techniques pop to mind:
From the documentation:
ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.
For example:
byteSlice, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal(err)
}
for b := range byteSlice {
// do stuff
}
This is should not be used for io.Reader
that are anything else than files (for example network connections) because an EOF condition may never happen, and so the program may block forever.
In your case, it is fine to use this technique, especially if you don't mind holding all the bytes in memory.
An alternative is also to use the io.ByteReader
interface through a bufio.Reader
, like this:
reader := bufio.NewReader(os.Stdin)
for {
b, err := reader.ReadByte()
if err != nil {
break
}
// do stuff
}
This is the closest to C's getchar()
loop.
Upvotes: 4