3

I have written a simple, interactive, program that expects inputs from the user. After it has read a specific input it takes a specific action, but first checks if the user has entered too many commands by reading from the stream any left over characters.

My problem is: if there are no left over characters in the stream it gets stuck until the user presses enter. Is there a way to override this?

This is the function that checks for left over characters in the input stream:

int check_end_of_stream(void){
    char c;
    c=getchar();
    for(; c!='\n' && c!=EOF; c=getchar())
        if(c!=' ' || c!=','){
            printf("You have written too many statements");
            printf(" in your command line!\n");
            return 0;
        }
    return 1;
}

Thank you in advance!

P.S. I am programming in Linux

AYR
  • 1,139
  • 3
  • 14
  • 24
  • 1
    you need timeout mechanism, use `read()` instead `getchar()` – Grijesh Chauhan May 11 '13 at 06:09
  • 1
    read this : [getchar() non-blocking](http://cboard.cprogramming.com/c-programming/130243-non-blocking-getchar.html) will help your – Grijesh Chauhan May 11 '13 at 06:12
  • 1
    There are ways to do it, but there are no standard ways to do it. The ways on Unix are different from the ways on Windows, so you should at least specify the system you want to work on. For Unix, you might look at the _curses_ library, or at non-blocking I/O options, and there are probably some other techniques such as timeouts too. – Jonathan Leffler May 11 '13 at 06:18

1 Answers1

0

Another solution is use getche() method this will not wait for enter to be pressed...

int check_end_of_stream(void){
char c;

for(c=getche(); c!='\n' && c!=EOF; c=getche())
if(c!=' ' || c!=','){
    printf("You have written too many statements");
    printf(" in your command line!\n");
    return 0;
}
return 1; 
}
avni
  • 1
  • 1
  • What library is getche() from? – AYR May 11 '13 at 06:36
  • 1
    Note that `getchar()` and relatives return an `int` and not a `char`. That's because they have to be able to return any valid `char` value plus a distinct value, EOF. Using `char` instead of `int` leads to one of two problems. If plain `char` is a signed type, then some valid character (often ÿ, y-umlaute, 0xFF, U+00FF, LATIN SMALL LETTER Y WITH DIAERESIS) is mis-recognized as EFO. If plain `char` is an unsigned type, then the value assigned to the `char` variable is never recognized as EOF. Neither is really acceptable. – Jonathan Leffler May 11 '13 at 17:38