Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C++

Name: Anon 2009-01-28 2:07

Hey, I am a complete noob to c++, and I need to know how to add strings.

Eg, I have:
a="one"
b="two"
c="three"

and I would like "d" to equal "onetwothree".

Thank you for any help

Name: Anonymous 2009-01-28 15:29

#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>

#define NOW() (gettimeofday(&here,NULL), \
    (here.tv_sec-there.tv_sec)*1000+(here.tv_usec-there.tv_usec)/1000)

#define HOWMANY 4000000

main(){
    int now,then;
    int i;
    struct timeval here,there;
   
    char
        *a="one",
        *b="two",
        *c="three";
   
    char *d;

    gettimeofday(&there,NULL);
   
    then=NOW();
    for(i=0;i<HOWMANY;i++){
        d=malloc((strlen(a)+strlen(b)+strlen(c)+1));
       
        strcpy(d,a);
        strcpy(d+strlen(a),b);
        strcpy(d+strlen(a)+strlen(b),c);
    }
    now=NOW();
    printf(">>5 took %d ms\n",now-then);

    then=NOW();
    for(i=0;i<HOWMANY;i++){
        d=calloc(strlen(a)+strlen(b)+strlen(c)+1, 1);
        strcat(d, a);
        strcat(d, b);
        strcat(d, c);
    }
    now=NOW();
    printf(">>11 took %d ms\n",now-then);

    then=NOW();
    for(i=0;i<HOWMANY;i++){
        volatile unsigned int la,lb,lc;
       
        la=strlen(a);
        lb=strlen(b);
        lc=strlen(c);
       
        d=malloc(la+lb+lc+1);
       
        strcpy(d,a);
        strcpy(d+la,b);
        strcpy(d+lb+lc,c);
    }
    now=NOW();
    printf(">>14 took %d ms\n",now-then);
}


Did not expect this:
>>5 took 1550 ms
>>11 took 1369 ms
>>14 took 1103 ms

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List