如何连接char* while循环?c++

How to concat char* while loop? c++

本文关键字:while 循环 c++ char 何连接 连接      更新时间:2023-10-16

基本上我想知道如何在for循环期间concat char*,并返回一个char*,这是deque中所有那些char*的concat。重要的是返回char*, 而不是 const char* string。

i've try this:

#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"); 

我怎样才能摆脱这个警告?我找到的每个解决方案都告诉我将"const"放在char*之前,但是我必须返回char*。tnx !

要摆脱警告并正确使用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 `` character added
                              //    by strcat()
    answer[0] = 0; // << set the initial '' character
    while (!q.empty()) {
        strcat(answer, q.front());
        q.pop_front();
    }
    std::cout << answer<< std::endl;
    return 0;
}

answer可以按照您的要求声明为char*