Thread: C user input question

  1. #1
    Registered User
    Join Date
    Jan 2021
    Posts
    2

    Question C user input question

    I am new here so I apologize in advance if this information is available in another topic, or if this is the wrong place to post this question.

    I'm not new to programming, but I am very new to the C language. I am trying to figure out the best way to take a user's input in the form of a string. The only real way I've seen is to declare a char array with a fixed value such a char input[20]; and then use something like fgets to store that input like fgets(input, sizeof(input), stdin);


    My question is, is there a way to deal with a user entering more characters than the size of the array allows. For instance, if I set the size of the array to 20 characters, but the user enters 50 characters, how do I store and print out all 50 characters?

    Thanks so much, and sorry if this is a stupid question.

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    Not a stupid question at all. There's a few solutions.

    You could make your input buffer reasonably large so it is unlikely to be too small. If you need to store many strings you can dynamically allocate space and copy the string from the large input buffer to the allocated space.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
     
    #define MAX_LINES 500
     
    int main() {
        char line[1024];
        char *lines[MAX_LINES];
        size_t nlines = 0;
     
        while (fgets(line, sizeof line, stdin)) {
            if (nlines >= MAX_LINES) {
                printf("lines overflow\n");
                break;
            }
            lines[nlines] = malloc(strlen(line) + 1);
            if (!lines[nlines]) {
                perror("malloc");
                exit(EXIT_FAILURE);
            }
            strcpy(lines[nlines], line);
            ++nlines;
        }
     
        for (size_t i = 0; i < nlines; ++i)
            printf("%s", lines[i]);
     
        for (size_t i = 0; i < nlines; ++i)
            free(lines[i]);
     
        return 0;
    }
    You can use a POSIX function (not in the standard library) that dynamically allocates the buffer for you.
    Code:
    // https://man7.org/linux/man-pages/man3/getline.3.html
    #define _POSIX_C_SOURCE  200809L
    #include <stdio.h>
     
    int main() {
        char *line = NULL;
        size_t n = 0;
     
        if (getline(&line, &n, stdin) == -1)
            perror("getline");
        else {
            printf("%zu: %s", n, line);
            free(line):
        }
     
        return 0;
    }
    Or you could write your own based on fgets, recalling that if the line that you've read doesn't have a newline (and eof hasn't been reached) then there's more to go. I just whipped this up so it may have a bug or two.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
     
    char *readline(FILE *in) {
        char buff[100], *line = NULL;
        size_t size = 0;
        while (fgets(buff, sizeof buff, in)) {
            size_t len = strlen(buff);
            char *tmp = realloc(line, size + len + 1);
            if (!tmp) {
                free(line);
                return NULL;
            }
            line = tmp;
            strcpy(line + size, buff);
            size += len;
            if (line[size - 1] == '\n') {
                line[size - 1] = '\0'; // remove '\n' if desired
                break;
            }
        }
        return line;
    }
     
    int main() {
        char *line = readline(stdin);
        if (!line) {
            printf("readline allocation error\n");
            exit(EXIT_FAILURE);
        }
        printf("%zu: %s\n", strlen(line), line);
        free(line);
        return 0;
    }
    Last edited by john.c; 01-11-2021 at 08:43 PM.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Quote Originally Posted by CGuy45
    My question is, is there a way to deal with a user entering more characters than the size of the array allows. For instance, if I set the size of the array to 20 characters, but the user enters 50 characters, how do I store and print out all 50 characters?
    If you're willing to use the non-standard but POSIX-standard getline function, then life is somewhat easier:
    Code:
    char *line = NULL;
    size_t len = 0;
    if (getline(&line, &len, stdin) != -1)
    {
        // make use of the string line of length len,
        // but note the newline character from the read is stored at the end
        // and you should free when done
    }
    If not, a standard approach would be to call fgets in a loop by using a char pointer and dynamic memory allocation: you keep reallocating space for the result string, appending the buffer to the result string until the newline character is found in the buffer (in which case you know you've read the entire line).
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Jan 2021
    Posts
    2
    Thanks so much! This was very helpful.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner User Input Question
    By anchorblue804 in forum C++ Programming
    Replies: 10
    Last Post: 09-10-2012, 04:37 PM
  2. Question about user input validaton
    By TexasKid in forum C Programming
    Replies: 11
    Last Post: 04-27-2012, 05:45 AM
  3. User determined input question
    By lyoncourt in forum C Programming
    Replies: 8
    Last Post: 09-30-2007, 06:10 PM
  4. newbie question regarding user input
    By cantore in forum C Programming
    Replies: 4
    Last Post: 03-05-2006, 08:57 PM
  5. Testing user input question?
    By Hoser83 in forum C Programming
    Replies: 18
    Last Post: 02-15-2006, 01:18 PM

Tags for this Thread