2012-12-15 4 views
0

Je souhaite insérer du texte (tableau char) dans un autre tableau char. Je pour cette strcpy, mais il montre parfois (pas toujours) des signes étranges, jetez un oeil:Comment insérer un tableau char dans un autre tableau char?

enter image description here

comment se débarrasser d'eux?

Heres mon code:

#include <string> 
#include <string.h> 
#include <time.h> 
#include <stdio.h> 
#include <iostream> 
using namespace std; 

const string currentDateTime() { 
    time_t now = time(0); 
    struct tm tstruct; 
    char buf[80]; 
    tstruct = *localtime(&now); 
    strftime(buf, sizeof(buf), "%X", &tstruct); 
    return buf; 
} 

char *addLogin(char *login, char buf[]) 
{ 
    string b(buf); 
    string l(login); 
    string time = currentDateTime(); 
    string res = time; 
    res += l; 
    res += b; 
    return const_cast<char*>(res.c_str()); 
} 

int main(int argc, char **argv) 
{ 
    char buf[1024]; 
    strcpy(buf, " some text"); 
    char *login = "Brian Brown"; 
    char *temp = addLogin(login, buf); 
    strcpy(buf, temp); 
    printf("%s\n", buf); 
    return 0; 
} 

ÉDITÉ:

const string currentDateTime() { 
    time_t now = time(0); 
    struct tm tstruct; 
    char buf[80]; 
    tstruct = *localtime(&now); 
    strftime(buf, sizeof(buf), "%X", &tstruct); 
    string b(buf); 
    return b; 
} 

et il semble bien fonctionner pour l'instant

+0

Dans memset pourquoi '& buf' il devrait être' buf' seulement puisque le nom du tableau donnera l'adresse – Omkant

+0

Ceci est C++ non C –

+0

N'est-ce pas pour quoi sprintf est? –

Répondre

2

De la fonction currentDateTime(), vous retournez une variable locale buf qui est un comportement indéfini. C'est certainement un problème gênant quand vous ajoutez les chaînes plus tard (avec celle retournée par cette fonction). En outre, la signature de la fonction est const string mais vous renvoyez un char*.

+0

édité, il semble bien fonctionner maintenant, merci! :) –

Questions connexes