I am facing problem when comparing two rune in if statement

package main

/*Write a program which prompts the user to enter integers and stores the integers in a sorted slice.

The program should be written as a loop. Before entering the loop, the

program should create an empty integer slice of size (length) 3.

During each pass through the loop, the program prompts the user to enter an integer to be added to the slice.

The program adds the integer to the slice, sorts the slice, and prints the contents of the slice in sorted order.

The slice must grow in size to accommodate any number of integers which the user decides to enter.

The program should only quit (exiting the loop) when the user enters the character ‘X’ instead of an integer.*/

import (“fmt”

    "sort"

)

func main() {

slice := make([]int, 0,3)

var temp rune

for true {

    fmt.Println("enter the integers\n")

    fmt.Scan(&temp)

    if(temp=='x'){

        break

    }

    slice=append(slice,int(temp))

    fmt.Println(slice)

}

sort.Ints(slice)

fmt.Println(slice)

}

First problem I found is that the code ignored the error returned from scan which was “expecting an integer” so I used scanf to scan for a character, but it was also considering the enter press as another character so I added “\n” to the pattern

then to get the digit from the rune you need to subtract from the ‘0’ rune to get the difference between them

here is the code after fixing the issues

package main

import (
	"fmt"
	"sort"
)

func main() {

	slice := make([]int, 0, 3)
	var temp rune

	for true {

		fmt.Println("enter the integers\n")

		_, err := fmt.Scanf("%c\n", &temp)
    if err!=nil {
      fmt.Println(err)
    }

		if temp == 'x' {
			break
		}

		slice = append(slice, int(temp - '0'))
		fmt.Println(slice)
	}

	sort.Ints(slice)
	fmt.Println(slice)
}
1 Like

An empty slice can’t have a length of 3, as if it has a length of 3, it contains 3 elements.

Please ask your teacher for proper and unambiguous wording in exercises.

That beeing said, whenever you have something that returns an error, then check it. Reading it in case of non-nil might help a lot to come up with a solution.

1 Like