2012-12-15 159 views
0

我想插入一些文本(char數組)到另一個char數組中。我用這個strcpy的,但有時顯示(不總是)奇怪的跡象,一起來看看:如何將char數組插入到另一個char數組中?

enter image description here

如何擺脫他們?

繼承人我的代碼:

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

,它似乎很好,現在

+0

在memset中爲什麼'&buf'應該是'buf',因爲數組名稱會給出地址 – Omkant

+0

這是C++不是C –

+0

這不是sprintf的用途嗎?編輯 –

回答

2

從功能currentDateTime()工作,你返回一個局部變量buf這是未定義的行爲。當你稍後添加字符串(以及由此函數返回的字符串)時,這肯定是個問題。

此外,該功能的簽名是const string,但您返回char*

+0

,現在看起來效果不錯,謝謝!:) –

相關問題