Thread: turning strings of unknown length into arrays

  1. #1
    Registered User hankspears's Avatar
    Join Date
    Mar 2002
    Posts
    14

    turning strings of unknown length into arrays

    How do I read a string into an array without either fixing the length of the string or getting the user to enter the length first?

    I thought this kind of thing might do it, but no joy:

    char *H;
    int i, n;

    gets(H);
    n = strlen(H);

    for(i = 0; i < n; i++)
    printf("%c", H[i]);

    printf("\n");

    I know I could do something like
    char H[100];
    but I wondered if there was another way?

  2. #2
    Registered User
    Join Date
    Feb 2002
    Posts
    14
    You might try this:

    char string[], c;
    int i = 0;

    while((c=getc(stdin)) != NULL)
    {
    string[i] = c;
    i++;
    }

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    You can't (directly)

    This is what you do

    Read (using fgets) input from the user into a fixed sized buffer (say 50 bytes).
    Allocate a 50 byte block of memory, copy the user input to this buffer, and append this buffer to the end of a linked list of buffers.
    Keep doing that until the user buffer contains the '\n' char (or some other end-of-input)

  4. #4
    Registered User hankspears's Avatar
    Join Date
    Mar 2002
    Posts
    14
    I guess this is stuff we haven't done yet. Linked lists seem to come up on this board all the time, so I should probably try and learn about them soon.
    Thanks for your help guys...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. storing strings in arrays
    By smp in forum C Programming
    Replies: 6
    Last Post: 12-16-2008, 09:37 AM
  2. Logic help with strings and arrays.
    By logithx in forum C Programming
    Replies: 2
    Last Post: 09-12-2008, 09:31 AM
  3. How to declare global arrays of unknown length?
    By ajm218 in forum C Programming
    Replies: 3
    Last Post: 08-07-2003, 09:13 AM
  4. UNICODE and GET_STATE
    By Registered in forum C++ Programming
    Replies: 1
    Last Post: 07-15-2002, 03:23 PM
  5. arrays of char strings
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 10-24-2001, 04:46 PM