Skip to content

Reading input

Read · 1 of 4

Read it all, hand it out one by one

On DSA sites, the input is written in a file and fed to your program. These three lines read all of it, split it into words and numbers, and give you next() to take the next one. Copy them to the top of every program that reads input.

Everything arrives as text, so turn numbers into numbers with Number(next()). Your program shouldn't print questions like "Enter a number".

1const input = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);
2let pos = 0;
3const next = () => input[pos++];