C++ 如何将字符数组插入到另一个字符数组中?
我想在另一个字符数组中插入一些文本(字符数组)。我用过这个strcpy,但它有时会显示(不总是)奇怪的迹象,看看: 如何摆脱它们 这是我的密码: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
#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;
}