我正在尝试将ostringstream复制到char*数组,并希望有人可以帮助我了解我的错误所在。我查看了论坛,发现了一些相似的东西,不幸的是我仍然无法将属性副本从 ostringstream 获取到 char*。简而言之,我试图通过以下方式复制到 char* 中:
ostringstream bld
bld<<"test"<<"is"<<"good"
const char * result = bld.str().c_str();
重现错误的完整代码如下。在这段代码中,我有两个函数,它们本质上是通过 ostringstream 构建字符串。在makeFilePath( ) 函数中,我构建了一个完整的文件路径(即/path/file.txt)。在add()函数中,我只是将另外两个 char* 数组添加到一个参数中以获取前缀 /path/file.txt 后缀。
问题是出于某种未知的原因,fullFilePath也更改为看起来像prefix /path/file.txt suffix。代码的最后三行将展示这一点。
我花了几个小时在这上面,想也许这是一个参考问题或别的什么。但是,我尝试过的都没有。任何想法如何克服这个问题?
谢谢!!
#include <iostream>
#include <sstream>
#include <string>
using std::cout;
using std::endl;
using std::string;
using std::ostringstream;
const char* add(const char *fileName) {
ostringstream bld;
const char *prefix = "prefix";
const char *suffix = "suffix";
bld << prefix << " " << fileName << " " << suffix;
string temp = bld.str();
cout << "in add(): \n\t" << temp << endl;
return temp.c_str();
}
const char * makeFilePath(const char *path, const char *name, const char *ext =
".txt") {
ostringstream bld;
bld << path << name << ext;
cout << "makeFilePath(), returning: \n\t" << bld.str()<< endl;
string temp = bld.str();
return temp.c_str();
}
int main(int argc, char **argv) {
cout << "=== PROJECT START ===" << endl;
const char * filePath = "\\Path\\";
const char *fileName = "FILENAME";
const char *fullFilePath = makeFilePath(filePath, fileName);
cout << fullFilePath before calling add():\n\t" << fullFilePath << endl;
const char* str = add(fullFilePath);
cout << fullFilePath after calling add():\n\t" << fullFilePath << endl;
return 1;
}