C ++:将stringstream转换为char *运行时错误

时间:2015-03-16 19:05:12

标签: c++ stringstream

我试图在C ++中转换" 1.txt"的字符串流。所以它等于" 1.txt"的char *值。我需要原始char *作为函数的参数,因此它不能是const char或其他任何东西。当我运行它时,我得到一个空白输出。为什么,我该如何解决?

#define SSTR(x) dynamic_cast< std::stringstream & >( (std::stringstream() << std::dec << x ) ).str()
int booknum = 1;
std::stringstream stringstream;
stringstream << SSTR(booknum) << ".txt";
std::vector<std::string> argv;
std::vector<char*> argc;
std::string arg;
std::string arg3;
while (stringstream >> arg) argv.push_back(arg);
for (auto i = argv.begin(); i != argv.end(); i++)
   argc.push_back(const_cast<char*>(i->c_str()));
argc.push_back(0);
int arg4 = argc.size();
for (int i = 0; i < arg4; i++)
    std::cout << &arg3[i] << std::endl;

2 个答案:

答案 0 :(得分:3)

这似乎非常复杂,而不是像。

std::ostringstream oss;
oss << booknum << ".txt";
std::string s = oss.str();
char* pString = new char[s.length() + 1];
std::copy(s.c_str(), s.c_str() + s.length() + 1, pString);

yourFunctionThatTakesCharPtr(pString);

delete[] pString;

答案 1 :(得分:0)

以下是转换代码示例:

#include <iostream>
#include <sstream>
#include <typeinfo>  //it's just to print the resultant type to be sure


int main() {int booknum=1;
    std::stringstream ss;
    ss << booknum<<"1.txt";
    char* x=new char[ss.str().length()+1];
    ss >> x;
    std::cout<<typeid(x).name();
return 0;}

输出:

Pc