turning strings of unknown length into arrays

This is a discussion on turning strings of unknown length into arrays within the C Programming forums, part of the General Programming Boards category; How do I read a string into an array without either fixing the length of the string or getting the ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,761
    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, 10:31 AM
  3. How to declare global arrays of unknown length?
    By ajm218 in forum C Programming
    Replies: 3
    Last Post: 08-07-2003, 10:13 AM
  4. UNICODE and GET_STATE
    By Registered in forum C++ Programming
    Replies: 1
    Last Post: 07-15-2002, 04:23 PM
  5. arrays of char strings
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 10-24-2001, 05:46 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21