2015-10-15 107 views
0

字符串我wan't初始化靜態字符緩衝區在下面的代碼中的字符串str,但我收到以下錯誤:初始化字符緩衝區在C++

error: cannot convert ‘std::string’ to >‘char’ in initialization

,如果我用

static char buf[500] = str.c_str(); 

我得到以下錯誤:

error: invalid conversion from ‘const char*’ to ‘char*’ 

下面是我的代碼:

std::string str = "<Version="+version+" Ret=\"false\"/>"; 
static char buf[500] = str; 
int len=strlen(buf); 
buf[len]='\0'; 
INFO("Static Buffer :: "<<buf); 
+3

那麼,這是因爲猜測編程不起作用。 –

+1

你的'buf [len] ='\ 0''是多餘的:根據定義,'len'是'buf'中已經存在的第一個''\ 0''的索引。你正在做的是用''\ 0''替換''\ 0''。 –

回答

3

首先,您不能直接從std::string初始化char[]。這是不可能的。即使你可以,你會寫= str,而不是= { str }

因此,您需要先創建陣列,然後手動將std::string的內容分配給它。可悲的是,數組不可分配,所以你將不得不使用「算法」來做到這一點。

這裏,我們去:

const std::string str = "Hello world"; 
static char buf[500] = {}; 
std::copy(
    // from the start of the string 
    std::begin(str), 

    // to the end of the string, or to 499 chars in, whichever comes first 
    std::begin(str) + std::min(str.size(), sizeof(buf)), 

    // into buf 
    std::begin(buf) 
); 

呸。

如果可以的話,這很可能是這種情況,避免它

如果你真的需要一個C字符串和std::string的內容,只要你需要訪問str.c_str()。一般來說,沒有必要保留原始數據,尤其是當您已經擁有適合做這項工作的工具時。

此外,由於你是不是初始化buf與數據,如果它的功能 - static,這個代碼可能沒有預期的效果。

+0

它給了我錯誤:'開始'不是'標準'的成員..也許結束並開始只能用於數組而不是字符串 –

+1

@yinyang您正在使用舊版本的標準來編譯代碼。 Pre-C++ 11沒有非成員'begin'和'end'。將'-std = C++ 14'(或者至少是'std = C++ 11')添加到編譯器選項中。 – emlai

+0

或者簡單地用'str.begin()'代替。一個小小的研究很長一段路要走:你可以在幾分鐘內從cppreference.com中找到它。 –

相關問題