如何连接char* while循环?c++
How to concat char* while loop? c++
基本上我想知道如何在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*
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- while循环中while循环的时间复杂度是多少
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 擦除while循环中迭代的元素
- 为什么我不能在 while 循环中创建线程?
- 退出简单while循环时出现问题
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 嵌套While循环不起作用(C++问题)
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 使用 GMP 的 while 循环出现问题
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么在 while 循环中返回表达式不起作用
- 如何使用 do while 循环确定最高值和最低值
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- OpenCV QT,显示视频的帧(不使用while循环)
- 在 while 循环中使用 pow() 函数 C++
- C++ 制作/命名不初始化的向量(在 while 循环中)
- std::getline没有在while循环中重新请求用户输入