user1009835
user1009835

Reputation:

User input and inserting into an array

I'm new to C. I need to know how to ask for the user input, which could be an arbitrary number of words, and then put the characters into an array.

I know this shouldn't be too hard to answer, but Google is just confusing me.

Thanks in advance

Upvotes: 0

Views: 1615

Answers (2)

Søren Engel
Søren Engel

Reputation: 375

If I understand your problem correctly, what you need is to read user input of some unknown size, thus store this information into a char array, right? If this is the case, one possible solution would be to have an char array with which should be allocated to a default fixed size, this dynamically reallocate it's size on the fly.

Once looping over the characters of the input, while verifying that you haven't hit an EOF, you should append the char to the array. The trick is then to check whether the array is large enough to hold the characters from the user's input. If not, you have to reallocate the array's size.

A sample implementation of a solution could look somewhat like this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned int len_max = 128;
    unsigned int current_size = 0;

    char *input = malloc(len_max);
    current_size = len_max;

    printf("\nEnter input:");

    if(input != NULL) {
        int c = EOF;
        unsigned int i = 0;

        // Accept user input until hit EOF.
        while (( c = getchar() ) != EOF) {
            input[i++] = (char)c;

            // If reached maximize size, realloc size.
            if (i == current_size) {
                current_size = i + len_max;
                input = realloc(input, current_size);
            }
        }

        // Terminate the char array.
        input[i] = '\0';

        printf("\nLong String value:%s \n\n",input);

        // Free the char array pointer. 
        free(input);
    }

    return 0;
}

Performance wise, I am not all to sure this may be the best solution, but I hope this may aid you on solving your problem.

Kind regards ~ E.

Upvotes: 1

Manos
Manos

Reputation: 2186

Start studying harder... A small help:

  1. For printing use printf()
  2. For user input use scanf() or fgets() (the second is better but a little harder...)

Upvotes: 0

Related Questions