Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在循环时连接字符*while?c++;_C++_Char - Fatal编程技术网

C++ 如何在循环时连接字符*while?c++;

C++ 如何在循环时连接字符*while?c++;,c++,char,C++,Char,基本上我想知道如何在for循环中concat char*,并返回一个char*,它是deque中所有那些char*的concat。重要的是返回char*,而不是常量char*或字符串 我试过这个: #include <iostream> #include <deque> #include <stdio.h> #include <string.h> using namespace std; int main() { deque <ch

基本上我想知道如何在for循环中concat char*,并返回一个char*,它是deque中所有那些char*的concat。重要的是返回char*,而不是常量char*字符串

我试过这个:

#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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
德克q;
q、 推回(“你好”);
q、 推回(“世界”);
char*answer=(char*)malloc(10);
而(!q.empty())
{
strcat(答案,q.front());
q、 pop_front();
}

cout要消除警告并正确使用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;
}
#包括
#包括
#包括
int main(){
标准:德克q;
// ^^^^^
q、 推回(“你好”);
q、 推回(“世界”);
char*answer=(char*)malloc(11);
//^^保留足够的空间以容纳
//已添加终止“\0”字符
//由strcat()编写

回答[0]=0;//尝试
deque q;
为什么不使用
string
?另外-您只为回答
分配了10个字节,malloc-hello+world=10个字符,
strcat
将添加一个空字符串终止符,因此您的代码将写入11个字节。可能是因为这是家庭作业。@πάῥεῖ,@巴拉克·马诺斯,我以前写过-不能使用它们。
#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;
}