2015-05-26 39 views
-4

基本上我想知道如何在for循環中concat char *,並返回一個char *,它是所有那些在deque中的char *的連接。其重要的是返回char *,而不是 const char * 字符串。如何concat char * while循環? C++

我已經試過這樣:

#include <iostream> 
#include <deque> 
#include <stdio.h> 
#include <string.h> 
using namespace std; 

int main() 
{ 
    deque <char*> q; 
    q.push_back("hello"); 
    q.push_back("world"); 
    char* answer = (char*)malloc(10); 
    while (!q.empty()) 
    { 
     strcat(answer, q.front()); 
     q.pop_front(); 
    } 
    cout << answer<<endl; 
    return 0; 
} 

輸出是真正的「HelloWorld」因爲我想,但我得到這個:

main.cpp:12:23: warning: deprecated conversion from string constant to 'std::deque<char*>::value_type {aka char*}' [-Wwrite-strings]           
q.push_back("world"); 

我怎樣才能擺脫這種警告?我發現每個解決方案都告訴我在char *之前加上「const」,但是我必須返回char *。 TNX!

+0

嘗試'deque q;' –

+0

爲什麼不使用'string'? –

+0

也 - 你只爲你的malloc分配10個字節,你的+世界= 10個字符,'strcat'將添加一個空字符串終止符,所以你的代碼將寫入11個字節。 – MuertoExcobito

回答

1

爲了擺脫的警告,並使用正確strcat(),你應該可以解決這樣的代碼:當你在你的問題要求

#include <iostream> 
#include <deque> 
#include <string.h> 

int main() { 
    std::deque <const char*> q; 
      // ^^^^^ 
    q.push_back("hello"); 
    q.push_back("world"); 
    char* answer = (char*)malloc(11); 
           // ^^ preserve enough space to hold the 
           // terminating `\0` character added 
           // by strcat() 
    answer[0] = 0; // << set the initial '\0' character 
    while (!q.empty()) { 
     strcat(answer, q.front()); 
     q.pop_front(); 
    } 
    std::cout << answer<< std::endl; 
    return 0; 
} 

answer可以保持聲明爲char*