23 March, 2013

Nitty-Gritty Things - 1

In this blog lets talk about some nitty-gritty implementation stuffs.

Okay. So assuming the reader knows C/C++

a) How to add time restrictions to user input?

To elaborate, we know in C, the user input is read using scanf/getc/getchar and in C++ using cin object.

So our objective is to add some time limit so that user inputs the value before the timeout.

a) You can do by calling a script written in bash/python etc from C code and evaluate.
b) May be create a thread and fire the thread when timeout happens.

Is there any other way? <Think before scrolling down>
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

http://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html
http://pubs.opengroup.org/onlinepubs/009695399/functions/alarm.html

After reading the above links, I came up with this.

#include<stdio.h>
#include<unistd.h>

#define TIMEOUT 5
int main()
{
        int t_iTemp;
        while( alarm(TIMEOUT), ( t_iTemp = getchar() ) != EOF )
        {
                putchar(t_iTemp);
        }
        return 0;

}

This program waits for 5 secs. If user doesn't input anything, it exits else just echoes the input
and waits for next 5 secs.

The idea is simple i.e to generate a signal based on timer.
But the important takeaway is about alarm function.


Okay lets see one more.

b) Say you are developing a clock app. Now you will have conditions for hours,seconds,mins etc

The thing we will talk is how do you display 00 when the clock moves from 59 in case of mins/secs and 23 in case of hour.

When we think about it, its nothing but printing "00". But remember here we are talking about numbers :-)

What happens when you assign 00 to a integer and print it. It should be printing 0 instead of 00.
So how do you print an integer as 00. This is what we will be talking.

<Think before scrolling>
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
..
.
.
..
.
.
.

You can use a format specifier :D

int a = 00;
printf("%d",a) -> 0
printf("%02d",a) -> 00

However there are functions which can replicate a given number/character which is the takeaway.
Check the below link.
http://www.cplusplus.com/reference/iomanip/setfill/


 int hrs = 0;
 cout<<setw(2)<<setfill('0')<<hrs<<endl;

Hope you enjoyed reading and got something out of it.
Please post comments/suggestions(if any).

No comments:

Post a Comment