Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Programming help

Name: Nobledragon 2006-09-10 16:38

Hi,

This is my first time posting to a 4Chan text board so i apologize if i seem a bit selfish asking for help in my first post but this is the only board that im confident has frequent users.

Here is my question:
For a homework assignment in C/C++ i need to have some code that will terminate the program if the user inputs a value outside of a preset range. Ive looked through the book and all the class notes i have and cant seem to find any reference on how to make that happen. I know someone here should be able to give me an idea on how to do this.

Name: Anonymous 2006-09-12 23:54

Here's a C version.  You can also do it with select(), and you probably would in a bigger program, but this is short and simple.  Note that unless you change the terminal mode to a more raw mode, you'll have to type "q<enter>".

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>

int main(void) {
        int in_fd = fileno(stdin);
        fcntl(in_fd, F_SETFL, O_NONBLOCK);

        int i = 0;
        int done = 0;
        char buf[11];

        for (; done == 0; i++) {
                int nread = read(in_fd, &buf, 10);
                if (nread > 0) {
                        buf[nread] = '\0';
                        if (strchr(buf, 'q') != NULL)
                                done = 1;
                } else if (errno != EAGAIN) {
                        perror("read");
                        exit(1);                             
                }
        }

        printf("Counted to %d.\n", i);
        return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List