Input¶
So far every program has worked on values written into its source. To work on data from
outside, a program reads standard input with input and eof, and its command-line arguments
with args.
Reading lines¶
input() reads the next line of standard input, without its newline. Since the input may have
run out, it returns a result, which Errors covers: ok of the line, or
err("end of input") once nothing is left. unwrap() gives the line, and stops the program
with cannot unwrap err: end of input if there was none. input("prompt ") writes the prompt
first, without a newline, for programs someone runs by hand:
name = input("what is your name? ").unwrap()
print("hello, " + name)
An empty line gives ok(""), which is not the end. To read every line, loop until eof() says
nothing is left, so each unwrap() finds one:
// reads "name score" lines from stdin and reports the best score
best_name = ""
best = 0.0
count = 0
total = 0.0
while not eof():
line = input().unwrap().strip()
if line == "":
cont
fields = line.split()
score = float(fields[1]).unwrap()
total += score
count += 1
if count == 1 or score > best:
best_name = fields[0]
best = score
print("read " + str(count) + " scores")
print("best:", best_name, best)
print("average:", total / float(count))
Given this input,
ada 91.5
grace 88
linus 72.25
margaret 97
it prints
read 4 scores
best: margaret 97.0
average: 87.1875
Run it with the input redirected from a file, or piped from another program:
stone run scores.stn < scores.txt
cat scores.txt | stone run scores.stn
Turning text into values¶
Everything read is a str, so a few builtins turn text into other values and back:
line.strip()removes spaces, tabs, and line breaks from both ends.line.split()breaks a line into words at runs of whitespace, andline.split(",")breaks it at each comma, keeping empty fields.int("42")andfloat("2.5")read numbers, allowing whitespace around them, and give results:ok(42)andok(2.5). Text that is not a number, such asint("4x"), gives anerrnaming the text, likeinvalid literal for int() with base 10: '4x'..unwrap()takes the number out, stopping the program on such text, and Errors shows how to handle it.str(value)goes the other way, giving the textprintwould write, so"n = " + str(3)is"n = 3".
Command-line arguments¶
args() returns the arguments given after the program as a list[str], without the program’s
own name:
total = 0
for a in args():
total += int(a).unwrap()
print(total)
stone run sum.stn -- 1 2 3 # prints 6
stone build sum.stn && ./build/sum 1 2 3 # prints 6 too
stone run gives the program everything after --, even arguments starting with -, so
stone run sum.stn -- -5 --x gives it ["-5", "--x"]. A built executable needs no --, since
every argument is its own.
Next, Modules.