:
Hello every one.
I have described what program has to do and what i have did plz help me.
Program has to take input from the user(i1) and print it, but if the user doesn't give any within 2 seconds program has to print some other variable(i2) ( which is given a default value). For the delay of 2 seconds I have used sleep(2). I am using Linux for coding.
hoping for a early reply.

#include<iostrem>
#include<stdlib.h>
using namespace std;
int main()
{
int i1,i2;
i2=0;
t=0;
cout<<enter the value<<endl;
cin>>i1;
t=1;
sleep(2);
if(t==0)
{
  cout<<i1;
}
else
{
  cout<<i2;
}
return 0;
}

Recommended Answers

All 4 Replies

#include<iostrem>    //you mean #include<iostream> right?

you forgot the a

ya u were right ,but my problem is not that . it is with the logic

It compiles =)

#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
	int i1,i2;
	i2=0;
	int t=0;
	cout << "enter the value" << endl;
	cin>>i1;
	t=1;
	sleep(2);
	if(t==0)
	{
  		cout<<i1;
	}	
	else
	{
  		cout<<i2;
	}
	return 0;
}

Dunno what the program is expected to do!

The cin >> i1 is a blocking call. That means it will wait forever for input to be available and you will not reach the sleep until the user enters something. You can wait for input to become available in linux by using select . Example:

#include <stdio.h>
#include <sys/select.h>

int main () {

    int rv = 0;
    fd_set fds;
    struct timeval tv = { 2, 0 }; /* two seconds */
    FD_ZERO (&fds);
    FD_SET (fileno (stdin), &fds);
    rv = select (fileno (stdin) + 1, &fds, NULL, NULL, &tv);
    if (rv < 0) { fprintf (stderr, "Error: select\n"); return 1; }
    if (FD_ISSET (fileno (stdin), &fds)) {
        char foo[255] = {0};
        fgets (foo, 255, stdin);
        printf ("You entered: %s", foo);
    } else {
        printf ("Timeout: No input in 2 seconds\n");
    }
    return 0;
}

The problem with the above is that the entire input (including newline) has to be entered before the time expires as select is not sensitive to the keyboard events. You would need to put the device into raw mode to handle a single character at a time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.