Seed packet label
A garden shop prints a label for every seed order. The label shows the plant name, the number of packets ordered and the total number of seeds in the order. Read the three values and print one line in exactly this form: <name> x<packets> = <total>, where <total> is the number of packets multiplied by the seeds in one packet. Keep the plant name exactly as given; it may contain spaces.
Input
Three lines: the plant name (1-30 characters, letters and spaces), the number of packets (an integer), and the number of seeds in one packet (an integer).
Output
One line: <name> x<packets> = <total>.
Example 1
Input
Basil 3 50
Output
Basil x3 = 150
3 packets of 50 seeds each hold 150 seeds.
Example 2
Input
Runner Bean 1 1
Output
Runner Bean x1 = 1
A name with a space is printed unchanged; 1 packet of 1 seed is 1 seed.
Constraints
- 1 <= packets <= 1000
- 1 <= seeds per packet <= 10000
- The name has 1-30 characters and contains only letters and spaces
Hints
Hint 1 of 3
The starter already reads the three values into name, packets and seeds_each; you only need to compute one product and print one line.
Hint 2 of 3
println! takes a format string with {} placeholders and fills them with the arguments that follow, in order.
Hint 3 of 3
println!("{} x{} = {}", name, packets, packets * seeds_each) prints exactly the required line.
Solution
Show a reference solution and explanation
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
let mut lines = stdin.lock().lines();
let name = lines.next().unwrap().unwrap().trim().to_string();
let packets: u64 = lines.next().unwrap().unwrap().trim().parse().unwrap();
let seeds_each: u64 = lines.next().unwrap().unwrap().trim().parse().unwrap();
let total = packets * seeds_each;
println!("{} x{} = {}", name, packets, total);
}
Why it works
The program shows the shape of almost every Rust exercise here: lock standard input, pull lines off it with lines(), turn text into numbers with parse(), and print with println!. The u64 annotations on packets and seeds_each tell parse() which type to produce; the product of two u64 values is another u64, so nothing needs converting before printing. {} in the format string is filled in order by the arguments, and the literal characters around the placeholders (x, =) are printed as they are. Trimming the name line removes a stray carriage return or trailing space without touching the spaces inside the name.
Lesson for this exercise: Rust Syntax and Your First Program