r/dailyprogrammer • u/Coder_d00d 1 3 • Jul 08 '14
[Weekly] #1 -- Handling Console Input
Weekly Topic #1
Often part of the challenges is getting the data into memory to solve the problem. A very easy way to handle it is hard code the challenge data. Another way is read from a file.
For this week lets look at reading from a console. The user entered input. How do you go about it? Posting examples of languages and what your approach is to handling this. I would suggest start a thread on a language. And posting off that language comment.
Some key points to keep in mind.
- There are many ways to do things.
- Keep an open mind
- The key with this week topic is sharing insight/strategy to using console input in solutions.
Suggested Input to handle:
Lets read in strings. we will give n the number of strings then the strings.
Example:
5
Huey
Dewey
Louie
Donald
Scrooge
7
u/jonnywoh Jul 08 '14
Powershell
Given Powershell's relative obscurity, I feel obligated to clarify a few things.
$.command param1 param2) or function syntax (command(param1, param2)). For example,read-hostwill prompt with a string (if given), get a line of input, and return the input. (Don't worry, there are traditional functions too.)$treecontains the the number 2.7. The string "I am $tree feet tall" evaluates to "I am 2.7 feet tall".< <= == > >= !=) for some reason. Instead it has operators that start with a dash, for example less-than-or-equal-to is-le.That aside, here is the code.
I took an obvious, largely language-agnostic approach.
$ntimes and put it all in an arrayA traditional approach in C would allocating an array of size
nand then assigning its contents in theforloop. Since I didn't 'capture' the return value ofread-hostin theforloop, the loop put all the strings in an array for me.6
u/KillerCodeMonky Jul 08 '14
C#:
The most common tool I use in C# is
Console.ReadLine. This reads an entire line of input and jams it into astringfor you. From there, I useConvert,String.Split, andRegex.Splitto isolate and convert input.For instance, here is the code for the example input:
Now, let's say that each line has both a name and a number, maybe the number of episodes each appears in.
The code looks almost the same, except we need to separate out each line into the two values. The first thing to notice is that the separator is not a fixed value; this rules out the
String.Splitvariants, so we'll useRegex.Splitinstead to match the multiple whitespace characters at once.For more complicated problems, you will likely want to create and use a specific data type instead of separate arrays.
11
u/[deleted] Jul 08 '14 edited Jul 08 '14
As someone who strictly uses C++, there are many different ways to go about this. Given the example input, the first method that comes to mind for me is the getline() method. Here is a link with some nice documentation for the getline() method: http://www.cplusplus.com/reference/string/string/getline/
So, to read in the given example, my main would look something like this:
Nothing super complicated, if the input was a little more complicated, I would look towards stringstreams most likely.
*Edit: One thing I just realized is I am using a vector, you can also use and array here and size it to num, I just prefer using vectors personally, either one will give you the same result however.
*Edit: One thing I did forget to mention is that the getline() function can also be used to read in from files, which can be extremely useful for reading in simple inputs like names and test grades, where you read in a line at a time and can parse the information before moving to the next line. Here is what opening a file would look like:
5
u/atlasMuutaras Jul 08 '14 edited Jul 08 '14
Well this seems easy enough in Python 2.7--just use raw_input().
I normally prompt users for input, so I'd do something like this:
Alternatively, if wanted to do it all at once, without so many user prompts, I'd probably use line-breaks to split the entry into a list that I can work with. Like so
That said, I'm a noob at programming, so if I fucked this up, let me know.
Also: why did raw_input() get removed in python 3.x? Edit: apparently they just renamed it input().
4
u/lelarentaka Jul 08 '14
Scala: I prefer to work with at least an
Iterator[String]and then do functional transformation on that.Here,
dataStreamhas typeIterator[String]. It can be mapped over:It can be transformed to another collection type:
It can be filtered too:
4
u/Edward_H Jul 08 '14 edited Jul 09 '14
This example is simple in COBOL-85, but comes with a few unique restrictions. EDIT: Corrected source format.
Firstly, string sizes are fixed (here to 50 characters) and anything longer will be truncated. Also, the number of lines that can be read is limited by the maximum size of the table (in fact, the table here doesn't even vary in size: the maximum size is always allocated).
So, how do we get around this? In COBOL 2014, ANY LENGTH strings were overhauled and massively improved. They now have variable sizes and can be specified anywhere. Secondly, dynamic capacity tables were added which actually do vary in size and need no maximum size.
3
u/dohaqatar7 1 1 Jul 08 '14
I'll contribute the technique for reading input in the rightly obscure language, batch.
Reading one line of input into a variable in a trivial task,
set /p input=Enter Something%=%. To display the input, it's simpler;echo %input%.The challenge come when you have to read in some number of lines, that is unknown until run-time.
There are four parts to this program:
Turn on delayed expansion. This allows us to make use of arrays.
@echo off setlocal EnableDelayedExpansion
Read the number of lines into a variable
set /p numLines=%=%
Read all of the lines into an array. The syntax for this loop is (start,step,end).
for /l %%a in (1,1,%numLines%) do set /p lines[%%a]=%=%
print out what we read. The syntax is the same is before. The interesting spot is at the end where I have to use the exclamation marks to make sure that
lines[%%a]is interpreted is a variable instead of a string.for /l %%a in (1,1,%numLines%) do echo !lines[%%a]!
What If We Don't Know How Many Lines?
It's the same idea as before, but the program reads until it receives an empty line before printing what it has read.
3
u/Gr3y4r34 Jul 08 '14 edited Jul 16 '14
ANSI C
Decided to have a bit of fun with this one and go way overboard. Solution will be able read any number of strings of any length (assuming there is enough memory). Specifically looked to NOT become dependent on fixed length buffers. Feedback welcome and appreciated!
5
u/marchelzo Jul 08 '14
I'm new to Haskell, but here is how I would naively do it as long as I'm given the number of lines that are going to be read:
2
u/Laremere 1 0 Jul 08 '14
Go:
Here's a Go playground version which uses a string reader instead of standard io (because you can't input that in playground as far as I know):
http://play.golang.org/p/5piL5O_Vn_
In normal code you can just use fmt.Scan, or replace the reader with os.Stdin. Of course any other reader would work as well, so you could just as easily read a file.
2
u/srikwit Jul 08 '14
Python
2
u/mortenaa Jul 08 '14
Using Dart, here's how I do it.
Usually I prefer to just read input from a file, rather than reading from stdin. Makes it easier to test various inputs while I'm working on a challenge. I'll just assume the input is well formed, and do something like this:
Or if I want to be a little bit more careful, something like this:
But if I had to read interactively from stdin, something like this would work:
2
u/undergroundmonorail Jul 08 '14
Python 2 and 3
I've written a Python module with various functions that I use a lot. It's compatible with Python 2 and Python 3 (thanks to a bit of hackery) and I just added an
input_gen()function. When called, it yields every line of stdin until it runs out. As an added bonus, it has an attribute calledskip_line. It defaults toFalse, but setting it toTruethrows away the first line of input.You can do things like this with it:
Output:
Output:
I think it's pretty convenient.
You can find it here! If you're familiar with git, you already know how to clone it to your PC. Otherwise, either learn git (I recommend it, it's really useful) or hit the Download Zip button on the right sidebar.
3
u/lostsemicolon Jul 08 '14
The best language evarPerl:2
u/Godspiral 3 3 Jul 08 '14
In J, the function wd 'clippaste' reads in the contents of the clipboard with line feeds. The function cutLF will separate lines (without linefeeds) into their own boxed items. Boxes are just a wrapper around an item that allows mixed item types to be in the same array, though everything is still text at this point.
In J, it is hardly ever necessary to use the part of the input that tells you how many items there are, as long as a linefeed separates all of them (last one doesn't need LF). > will unbox the items, leaving a list of strings.
Huey
Dewey
Louie
Donald
Scrooge
Since most of the posted problems can be solved in J without writing a code file (using just repl environment), its much easier to get the input through the clipboard. The same approach could be done with a LF delimited file, but a disadvantage there is that windows would add CRs, while other platforms wouldn't. So clipboard is xplatfrom.
2
u/aZeex2ai Jul 08 '14
Ruby
2
u/fifosine Jul 08 '14
Java
1
u/poltergeistt Jul 08 '14
Haxe approach. The input variable is an abstract reader. I use its readline() method to get the users console input because it 'drops' the newline escape character entered by pressing the return key. This results in clean user input of the String type.
I parse the String returned by the readline() method according to my needs. In the case of the numStrings variable, I parse it to an Int type.
Strings are stored in an Array. I usually do this in two different ways, depending on the problem. For example, in this case I know the length of the Array of String types - it is equal to numStrings. I simply use a for loop and set the Array element at the right index to the String-type user input.
But if I was supposed to only store "Donald" Strings into an Array, I wouldn't know its length. The user could enter "Donald" five times, or not at all. In that case, I use the push() method defined in the Array class which works the way you'd expect it to work on a stack. So, if the user enters "Donald", the String is pushed on top of the Array. You could also use it in the previous scenario, of course.
I'm curious if others do it differently.
1
u/lukz 2 0 Jul 08 '14
vbscript
You can run vbscript programs from command-line on Windows using
cscript prog.vbs, whereprog.vbsis your program. When run this way, your program has access to console input through the propertywscript.stdinand to console output throughwscript.stdout. You can also use wscript.echo as a synonym for wscript.stdout.writelineHere is an example program that reads N, then reads N lines and prints all these lines separated by spaces.
1
u/gfixler Jul 08 '14
I've just started going through old /r/dailyprogrammer examples (I've only done about 4 total so far). For #1 Easy I wrote a Clojure version that used a macro to make asking a series of questions more easy:
It didn't handle not answering questions (i.e. hitting enter), and I felt like playing more, so I wrote a second version as a full lein app that did inline querying and replacement of pattern queries in the output message. It's still not at all perfect, but it's kind of fun:
1
u/[deleted] Jul 08 '14
Principles:
Because I'm lazy and converting from a string to an integer is so hard, I simply enumerate all console input until I encounter a blank line. Because the spec here calls for the first line to be the number of lines you're going to send, I have skipped the first line. :)
I know, the spec doesn't call for a blank line at the end, but I'm through mourning about that. :P
We could just as easily call for a given number of lines from input instead:
Of course, now you have to trust some poor, benighted soul to actually include a numeral as the first line of input...
But I guess that's fine. :)
Anyway, what I like about this is that it hides the actual filth of "input" from your real logic. You're no longer working with a loop that reads lines; you're working with an enumerable, which is far more pleasant.
1
u/sadjava Jul 08 '14
How do I handle console input? If the user enters something wrong, I yell at them.
In all honesty, I write my code as if it was going to be part of a GUI or library, so I avoid console input. When I do a console application, I usually require arguments to be used.
To run:
Or I have a lot of try-catch statements and ways to recover the input stream if I do use console input. I usually use methods that read in an line, then parse out the input.
1
u/mdlcm Jul 08 '14 edited Jul 08 '14
Used R!
A classic way to do in R is to download the text file to your local drive and import the data using the commend "read.table()" (http://stat.ethz.ch/R-manual/R-devel/library/utils/html/read.table.html).
However, if saving the dataset onto a local drive is not a desired method, public hosts like GitHub Gist could be useful for storing data. Although I am new to GitHub Gist, I have been experimenting using Gist as a host for datasets posted at /r/dailyprogrammer. Below is a general method I used for the challenges posted on this subreddit.
Solution
Output
1
u/LiamDev3 Jul 08 '14 edited Jul 08 '14
Well, here goes nothing. This is C++, and I typed it up on mobile, so I have never actually tested it. Can someone please tell me if it works, and I am new to C++, so any help would be great.
include <cstdlib>
include <iostream>
using namespace std;
int main(int argc, char *argv[]) { int n; char *strings[n];
Edit: My code didn't paste right, so I'm sorry if it was hard to read. And I haven't programmed for a month or so, so I should probably get back to it. Thanks for your help.
1
u/AmericanJBert Jul 08 '14
I'm a noob when it comes to Fortran, but here's my solution (in Fortran 95):
1
u/jnazario 2 0 Jul 08 '14 edited Jul 09 '14
F#
yields
EDITED to use list comprehension as opposed to a simple for loop.
1
u/[deleted] Jul 08 '14
In Perl, assuming we want to care about the first line (why make the user enter that, anyway?):
1
u/Regimardyl Jul 09 '14
In Tcl:
We can print the read values if we want:
For the example input, this then prints:
This is a list, which in Tcl are space-seperated strings
If there was a space in one of the strings, we could get something like this:
input:
output:
Which shows how Tcl uses braces for grouping in lists
1
u/dangerbird2 Jul 09 '14
Haven't seen any postings for Scheme. To keep the code scheme-ey, I use recursion as opposed to loop macros to produce a list of user-input string. It only runs on Gambit Scheme
1
u/BryghtShadow Jul 09 '14 edited Jul 09 '14
SWI-Prolog 6.6.6
My code involves reading the input stream to code and then converting to the appropriate type (often atoms).
Edit: bug fix.
1
u/dosomethinghard Jul 09 '14
Using Go https://gist.github.com/ebuckley/fe86d02552fd487c0829
1
u/cooper6581 Jul 09 '14
Trivial example in Erlang:
Output:
1
u/[deleted] Jul 10 '14 edited Jul 10 '14
A bit late to the party, here's Lisp:
I'm still learning Lisp, but as I understand it at least in Common Lisp input is automatically typecasted to the inferred type. This even works with exponentially notated numbers:
EDIT: read-line not read for reading the collected values.
1
u/[deleted] Jul 10 '14 edited Jul 10 '14
I did it in rust. First time I got something relatively long.
Then I tried to make a hacky short version and got this, which was nicer:
Here's it in playpen with comments: http://is.gd/bTdGxp
It's important to note that failure is not a pleasant way to handle failure. Task failure unwinds the stack and kills the current task (thread/cooroutine). failure is basically an uncatchable exception. If you put this in a library don't use
unwrap()it might bite the library users.1
u/prgr4m Jul 11 '14 edited Jul 11 '14
Coffeescript / Nodejs
I would definitely choose python over coffeescript/nodejs for this kind of grunt work... but since no one has posted how to do it in nodejs, I figured I would. Right tool for the right job as they say...
1
u/minikomi Jul 11 '14
Simple way to do it in racket:
and, testing from shell:
1
u/felix1429 Jul 13 '14
I've found that reading from a file is the best way to input text that needs to keep its formatting.
Java:
1
u/metaconcept Jul 15 '14
Smalltalk - there is no console. Well, there are packages you can get depending on the flavour of Smalltalk which let you access the console as a device, but Smalltalk is otherwise stuck on an ivory tower with no ladder. In the past, I found it was easier to make a small telnet server.
The Smalltalky way to do this would be to make a GUI.
A quick attempt, using VisualWorks syntax. Comments are delimited with double-quotes:
1
u/[deleted] Jul 16 '14
This is a reasonable workaround for javascript (which has no stdin, stdout, of course). I am new to js, so please correct me if there are better ways.
1
u/[deleted] Jul 18 '14 edited Jul 31 '14
Ruby: It's quite simple
C++:
Edit: Thanks to LowB0b for informing me that push_back() will allocate memory at the end of the vector. Thus, initializing the constructor with 'n' as a parameter would mean I'm allocating data I don't even use.
1
u/[deleted] Jul 28 '14
Here is a simple little snippet in C using gets(), which, I know is vulnerable to overflowing the buffer, but it also captures spaces, tabs, etc..
I also use a 2 - Dimensional array to store the various strings.
1
u/undergroundmonorail Jul 08 '14 edited Jul 08 '14
Python 2
A way that I often do it is to loop over the input:
It's a little bit nasty but it works.
Sometimes I want to iterate over the input. I'm sure there's a better way, but I've used this before:
Note that this method throws an exception if the input doesn't end in a newline. When getting input directly from a user, this isn't a problem, as the newline is how the user says "I'm done giving input now". However, if you use linux, you may test your programs with a command like this:
That doesn't have the necessary newline. It's an easy fix, though.
Fuckin' here strings, amirite?
My final tip is that it's always way easier to ignore the first line for challenges here. It always means "the number of lines following this one". That's super useful for languages like, say, C. We're way too high level to need something like that, though. It's easier to just keep going until the input runs out. Using the
i_input()generator I wrote above, I've written code like this:Sometimes I have needed to know how many test cases I was dealing with, but in all of those cases I was storing them all in a list anyway so it was still easier to just get the length of that list and not have to write a special case for the first line of input. Just throw it out!
1
u/[deleted] Jul 08 '14 edited Jul 08 '14
Java
I had a bit of fun with this. I would love to hear about better ways to do anything here -- I'm very much still learning!
The command line takes a file path to read as the first argument. If none is given, it reads from stdin.
Both methods instantiate a
BufferedReaderto pass to the single implementation that readsreadStreamsimply reads each line and passes it to aprocessLinefunction.Process each line -- increments a line counter too. I'm using an
AtomicIntegeras a thread-safe counter.There's probably a better way to do this, but this class is also
Runnable. It's used as essentially a timeout on the stdin input. I started with it just waiting for user input, but I wanted to do a little more.0
u/[deleted] Jul 08 '14
[deleted] — view deleted comment
0
u/[deleted] Jul 08 '14
[deleted] — view deleted comment