GO: Input/output from Standard I/O

In this article we show how to input/output from standard I/O using a GO program. If we wanted to get the variables A and B from the terminal and save the output in a file outFile.dat, we could use the modified code program2.go. (Here we assume that the executable program2 has been created using the command go build program2.go).

/* program2.go */
package main

import ( "fmt" ; "math" )

func curve(x, A, B float64) float64 {
   y := A * x * math.Exp(-1.1*x)
   if x > B {
      y = y + B*(x-B)*math.Exp(-1.1*(x-B))
   }
   return y
}

func main() {
   var A, B float64
   fmt.Scan(&A, &B)
   for i := 0; i < 100; i++ {
      x := float64(i) / 10.0
      fmt.Println(x, curve(x, A, B))
   }
}
  • The command required for execution (in a bash terminal on any system) is: ./program2 > outFile
  • In a Windows cmd or command terminal, you can use the command: program2 > outFile
  • In both cases we enter A and B on the keyboard:
    • 5 4
  • To take input from inFile and save output to outFile we use the command (in bash):
    • ./program2 < inFile > outFile
  • In Windows:
    • program2 < inFile > outFile
  • Here inFile is created beforehand using a text editor and contains
    • 5 4