#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2002
    Posts
    0
    Rep Power
    0

    Question building a string


    i have a function which returns bytes of data 1 at a time.

    i want to concatenate that bytes together to get a string

    like the gets function does, only i don't get this input from the keyboard

    it sounds easy, but i am new to the c language, so i would like to know how to do this

    thank you

    andre
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Oct 2000
    Location
    Back in the real world.
    Posts
    5,966
    Rep Power
    190
    i donīt think there is a pre-made function. you probably need to invent one like this:

    void addToString(char *s, char c) {
    int len;
    len=strlen(s);
    (s+len)^=c;
    (s+len+1)^=0;
    }

    this one requires that you allocated enough memory for s before.
  4. #3
  5. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,640
    Rep Power
    4247
    M. Hirsch, the code you posted is conceptually correct, but it looks like you are confusing pascal and c pointer syntax there :). Seriously though, there is a function called strcat, which concatenates two strings (rather than a string and a byte). Maybe you can do something like this:
    Code:
    void addToString(char *s, char c) {
      char tmp[2];
      tmp[0] = c; tmp[1] = '\0';
      strcat(s, tmp);
    }
    However, the big issue with the above (the same is true for M. Hirsch's code as well) is that the length of the string is evaluated each time and an extra char is then tacked on to the end. For a long string, this might be a wasteful operation to determine the string length each time. A better way to do this IMHO would be something like this:
    Code:
    char *ptr;
    char ch;
    ptr = char_str; // char_str is assumed to be the string array that was allocated previously
    
    while (GetByte(&ch)) {
        *ptr = ch;
        ptr++;
    }
    
    *ptr = '\0';
    where GetByte() is assumed to be your function that returns a byte at a time. The above code does not recompute the string length each time and is therefore faster.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Oct 2000
    Location
    Back in the real world.
    Posts
    5,966
    Rep Power
    190
    got me ;) iīm a delphi phreak

    seems like i need some practise in C...

IMN logo majestic logo threadwatch logo seochat tools logo