Thursday, November 27, 2014

Reading input from standard input

Problem statement

Now a days,big companies usually have their first round of interview online where they outsource test to either HakerRank or some other such website. One thing which is of at most importance in those tests is that we need to pass test cases which are run when you submit the code. These test cases are taken from file or standard input. For example, question based on array and array elements will be given on one line on STDIN, without mentioning the size of the array first. So input will be like
34 45 56 78 89 100. We need to read this input, process it and then produce the output.

Many a times, we flounder when we need to take inputs from stdin as we are not used to such things in our day to day coding. In this post I am covering methods in which you can read inputs for STDIN.

Solution

Whenever we are reading from STDIN, use fgets() to read the entire line from it. fgets() takes three arguments, first the buffer where it will read the input to, second size of input to be read in bytes and third the source of input which in our case will be STDIN. For details refer : fgets()

Now, once we have read the entire line of integers from STDIN in buffer, we need to segregate each integer from it. There comes the sscanf ()function.
sscanf() takes three arguments, first the buffer which is read by the fgets(), second the format string of input like "%d" for integers, and last the place where it need to put the scanned input. For more details on sscanf please refer : sscanf()

Now, let's put this all together and see if it works. In following code, I am scanning a list of numbers from STDIN and storing them in an array and then printing that array. If you have notice, in code we have something called as n which is also read with sscanf, it helps us in finding the pointer in the buffer from which we need to read next integer from, else we will always be reading the first integer only.

Now look at when there are multiple lines are given as input from the STDIN like below are the edges of a particular graph, from which we need to store graph representation:
2 3
4 5
6 8
Reading of this kind of input is very similar to what we saw above. Only thing is now we need to put fgets() in while loop till we have input to read from line.

Notice one thing that now, we are checking return value of sscanf() against two because now we are explicitly reading two integers from the line, whereas in previous case we were reading one integer at a time.

Please let me know if you could not follow something or want to add to it.
Blogger Tricks