How to get the input size and input element, then print to the console?

package main
/*
Input  size : 2 and 6
input element :  32 91 and 22 90 45 43 2 57  

expected : 32 and 22 90 2

got : empty console
*/
import (
	"bufio"
	"fmt"
	"os"
)

func evenNumbers(size []int) []int {
	var input []int
	for _, v := range size {
		if len(size)%2 == 0 {
			input = append(input, v)
		}
	}
	return input
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	var slice []int
	num := evenNumbers(slice)
	for _, result := range num {
		fmt.Print(result)
	}
}

The documentation of (*bufio.Scanner).Scan says:

Scan advances the Scanner to the next token, which will then be available through the Bytes or Text method.

So you have to call Scan to load the first token into the scanner’s buffer and then you call (*bufio.Scanner).Bytes to get the actual value out. You probably want to put the call to Scan in a loop to keep reading tokens out, parse them into integers (maybe with strconv.Atoi), and then append them to an []int slice.

According to bufio.NewScanner’s documentation, by default, tokens are separate lines. If you want to read words on the same line like 32 91, then you probably want to change the scanner’s bufio.SplitFunc with (*bufio.Scanner).Split and pass in bufio.ScanWords.

here you are getting the same result all the times. I think you mean if v % 2 == 0 …

1 Like