Search code examples
ciofgetsgetc

Input of maximum 256 characters in C


I/O question:

I was asked to get an input from the user and parse it. The problem is my program is supposed to be able to handle any length of input and to treat any input line longer than 256 characters as invalid and print a message accordingly.

Currently I'm using fgets to recieve the input line and strtok to parse it later on, but it's a problem with a very long input line.

How could I solve this problem?

my code so far:

char userInput[1024];
        char *token = NULL;

        while (!feof(stdin)) {
                    fflush(stdin);
                    if (fgets(userInput, 1024, stdin) != NULL) {
                    token = strtok(userInput, " \t\r\n");
                        if (token != NULL) {



                            if (strncmp(userInput, "fiver", 5) == 0) {

                                            printf("5");
                                            }
                            else if (strncmp(userInput, "four", 4) == 0) { printf("4");}

Solution

  • Have an array or 257 or 258 characters (depending on whether to count the newline among those 256) and read into it using fgets, passing in the size 257 or 258. Then check the length of the string with strlen(). If the strlen(buf) is exactly the maximum length of the line including the newline, then check the strlen(buf)-1th character - if it is \n it is fine, otherwise you've got a too long line.


    Or just use fgetc instead of fgets, counting until '\n' or 256 whichever comes first.