Skip to content

Instantly share code, notes, and snippets.

@rayning0
Last active March 12, 2020 00:50
Show Gist options
  • Save rayning0/1e1e1f5a3869e01b25e7189766259db2 to your computer and use it in GitHub Desktop.
Save rayning0/1e1e1f5a3869e01b25e7189766259db2 to your computer and use it in GitHub Desktop.
Different ways to read/write input in Golang
// Different ways to read/write input in Golang:
// ----------HackerRank----------
// read from 3 nums from command line
package main
import "fmt"
func main() {
var n int
var a int
var b int
fmt.Scan(&n)
for i := 0; i < n; i++ {
var sum int
fmt.Scan(&a, &b)
sum = a + b
fmt.Println(sum)
}
}
//-----------HackerRank-------------
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
// Complete the makeAnagram function below.
func makeAnagram(a string, b string) int32 {
freqa := make(map[string]int)
freqb := make(map[string]int)
return 0
}
func main() {
reader := bufio.NewReaderSize(os.Stdin, 1024*1024)
stdout, err := os.Create(os.Getenv("OUTPUT_PATH"))
if err != nil {
panic(err)
}
defer stdout.Close()
writer := bufio.NewWriterSize(stdout, 1024*1024)
a := readLine(reader)
b := readLine(reader)
res := makeAnagram(a, b)
fmt.Fprintf(writer, "%s\n", res)
writer.Flush()
}
func readLine(reader *bufio.Reader) string {
str, _, err := reader.ReadLine()
if err == io.EOF {
return ""
}
return strings.TrimRight(string(str), "\r\n")
}
//-----------Prompt user from command line--------------
import (
"fmt"
"os"
)
func main() {
name := readInput("Enter your name")
fmt.Printf("Hi %v", name)
}
func readInput(p string) (d string) {
buf := make([]byte, 100)
fmt.Printf("%v: ", p)
n, err := os.Stdin.Read(buf)
if err != nil {
return ""
}
return string(buf[:n-1])
}
//-------------------------
// Read and write file line by line
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
infile, err := os.Open("/Users/rgan/go-interpreter-compiler/input.txt")
outfile, err := os.Create("/Users/rgan/go-interpreter-compiler/output.txt")
if err != nil {
log.Fatal(err)
}
defer infile.Close()
defer outfile.Close()
scanner := bufio.NewScanner(infile)
for scanner.Scan() {
fmt.Println(scanner.Text())
fmt.Fprintln(outfile, scanner.Text())
if err != nil {
fmt.Println(err)
return
}
// numBytes, err := outfile.Writeln(scanner.Text())
if err != nil {
fmt.Println(err)
outfile.Close()
return
}
// fmt.Println("Wrote", numBytes, "bytes")
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment