我想将一些文本(字符数组)插入另一个字符数组。我使用了这个 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;
}
编辑:
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;
}
它现在似乎运作良好