简体   繁体   中英

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:

在此输入图像描述

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

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* .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM