Brian Brown
Brian Brown

Reputation: 4311

How to insert char array into another char array?

I want to insert some text (char array) into another char array. I used for this strcpy, but it sometimes shows (not always) strange signs, take a look:

enter image description here

how to get rid of them?

Heres my 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;
}

EDITED:

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;
}

and it seems to work well for now

Upvotes: 0

Views: 1372

Answers (1)

P.P
P.P

Reputation: 121377

From the function currentDateTime(), you return a local variable buf which is undefined behaviour. This is certainly cauing problem when you later append the strings (along with the one returned by this function).

Besides, the signature of the function is const string but you return a char*.

Upvotes: 2

Related Questions