Please read the new rule regarding the restriction on the use of AI tools. ×

Handling Standard Input in Go (1.17.6) #1

Revision en1, by hotpotcookie, 2022-02-01 14:45:34

Most of the cases that I've been worked on (doing some 800 rated problemsets), the input section will require 2 type of standard input, the iteration and the case statement.

For the iteration, I tend to use fmt library to get the input in int straight away to the variable's location via Scanf. For the case statement, it tends to be multiline that are refers to the iteration, so i use a slice that match the length index, then read each line in a for loop via ReadString from bufio.

Then i need to chop the strings with Fields since each entry have it's own new line in em, so theres a gap in between each case statment. Now each entry have stored in slice / array, and rdy to be proceed

package main
import ( 
  fmt "fmt"
  str "strings"
  os "os"
  buf "bufio" 
)

func main() {
  itr := 0;
  in := buf.NewReader(os.Stdin);
  _,_ = fmt.Scanf("%d\n",&itr);
  
  arr := make([]string,itr);
  for i := 0; i < itr; i++ {
    arr[i],_ = in.ReadString('\n');
    arr[i] = str.Fields(arr[i])[0];
  }  
  fmt.Println(arr);
}

PS: if each line required to have whitespaces in, then dont use Fields only on index 0 by removing the [0]

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English hotpotcookie 2022-02-01 14:45:34 1231 Initial revision (published)