Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将字符数组插入到另一个字符数组中?_C++_Arrays_String_Char - Fatal编程技术网

C++ 如何将字符数组插入到另一个字符数组中?

C++ 如何将字符数组插入到另一个字符数组中?,c++,arrays,string,char,C++,Arrays,String,Char,我想在另一个字符数组中插入一些文本(字符数组)。我用过这个strcpy,但它有时会显示(不总是)奇怪的迹象,看看: 如何摆脱它们 这是我的密码: #include <string> #include <string.h> #include <time.h> #include <stdio.h> #include <iostream> using namespace std; const string currentDateT

我想在另一个字符数组中插入一些文本(字符数组)。我用过这个strcpy,但它有时会显示(不总是)奇怪的迹象,看看:

如何摆脱它们

这是我的密码:

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

现在它似乎运行良好

从函数
currentDateTime()
返回一个局部变量
buf
,它是未定义的行为。当您稍后附加字符串(以及此函数返回的字符串)时,这无疑是一个问题


此外,函数的签名是
const string
,但是在memset中返回一个
char*

,为什么
&buf
它应该是
buf
,因为数组名会给出地址,这不是sprintf的作用吗?
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;
}