Sum the numbers on standard in
Bash + coreutils, 16 bytes
xargs|tr \ +|bc
Try it online!
There are two spaces after the \
. This works for negative numbers as well.
Explanation:
xargs # known trick to turn newlines into spaces, while adding a
#trailing newline when printing the result (needed for bc)
|tr \ + # turn spaces into '+'s
|bc # calculates the sum
You may wonder why tr \\n +|bc
isn't better, since it turns newlines directly into '+'s. Well, that has 2 unforeseen errors:
- if the input has a trailing newline, then it is converted to a trailing '+', hence there is no number after it to perform the addition
- and the most weird issue is that bc requires a trailing newline after the input, but you just replaced all of the input newlines with '+'s.
05AB1E, 2 bytes
|O
Explanation:
| Get input as array
O Sum
Try it online!
MATL, 2 bytes
Us
This expects the input in a text file called defin
.
Gif or it didn't happen:
Or try it online! (thanks to Dennis for the set-up!)
Explanation
When a MATL program is run, if a file called defin
is found (the name refers to "default input"), its contents are automatically loaded as text and pushed to the stack as a string before executing the code.
Function U
evaluates the string to convert it to a column vector of numbers, and s
computes the sum, which is implicitly displayed.