0

:
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;
}
4
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by L7Sqr
0
#include<iostrem>    //you mean #include<iostream> right?

you forgot the a

Edited by zeroliken: n/a

0

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

0

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!

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.