Go, lesson 3
Programs become useful when they react to input. In this course your programs read from standard input (stdin), the text typed in or piped to the program, and write to standard output.
fmt.Scan reads space- or newline-separated values straight into variables. You pass the
address of each variable with &, so Scan can fill it in:
With input 4 5 or 4 and 5 on separate lines, this prints 9. Scan looks at the
variable's type to decide how to read: an int reads a whole number, a reads a
decimal, a reads one word.
2 exercises to try what you just read.
float64stringScan also returns how many values it read and an error. For small exercises you can ignore
them, but in lesson 9 you will check them.
A string read with Scan stops at the first space. To read a full line, such as a name with
spaces, wrap stdin in a bufio.Scanner:
When the text is a number, convert it with the strconv package. strconv.Atoi turns text
into an int, and strconv.ParseFloat(s, 64) turns it into a float64. Both return the
value and an error; for now, ignore the error with _:
| Operator | Meaning | 7 ? 2 with ints |
|---|---|---|
+ | add | 9 |
- | subtract | 5 |
* | multiply | 14 |
/ | divide | 3 |
% | remainder | 1 |
Watch out: when both sides are integers, / throws away the fraction. 7 / 2 is 3. If you
want 3.5, convert first: float64(7) / 2. The remainder operator % only works on
integers and is perfect for "is it even?" or splitting seconds into minutes.
Go also has shortcuts that update a variable in place: x += 5, x -= 1, x *= 2, and
x++ / x-- to add or subtract one. In Go, x++ is a statement, not an expression, so
y := x++ is not allowed.
The math package has helpers for floats, such as math.Sqrt, math.Round and math.Abs.
Printf controls how numbers look. %.2f prints a float with two decimals. %02d pads an
integer with zeros to width two, which is handy for clocks:
Friends share a restaurant bill equally. Read the bill total (a decimal number) and the number of people (a whole number), separated by whitespace. Print what each person pays, with exactly two decimals.
Sample input:
Sample output:
A race timer records a run in whole seconds. Read one integer and print it as hours, minutes
and seconds in the form H:MM:SS, where minutes and seconds always have two digits.
Sample input:
Sample output:
var a, b int
fmt.Scan(&a, &b)
fmt.Println(a + b)import (
"bufio"
"fmt"
"os"
)
func main() {
sc := bufio.NewScanner(os.Stdin)
sc.Scan() // read the next line
line := sc.Text() // the line, without the newline
fmt.Println("You said:", line)
}n, _ := strconv.Atoi("42") // 42
price, _ := strconv.ParseFloat("2.5", 64)fmt.Printf("%.2f\n", 10.0/3) // 3.33
fmt.Printf("%d:%02d\n", 7, 5) // 7:0585.00 328.3337251:02:05