-4

I am trying to convert in C++ a stringstream of "1.txt" so that it is equal to a char* value of "1.txt". I need the raw char* as an argument for a function, so it can't be const char or anything else. When I run it, I get a blank output. Why, and how do I fix it?

#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;
Eric Morse
  • 7
  • 1
  • 3

2 Answers2

3

That seems very complicated, instead of e.g.

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;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • You could even replace `pString` with a `std::string` – Mooing Duck Mar 16 '15 at 19:16
  • @MooingDuck It depends on what the function does, as it's stated in the question that it takes a non-const pointer. – Some programmer dude Mar 16 '15 at 19:17
  • Then pass in `s.data()`. Oh, you mean it could take a pointer by reference and `delete[]` `new[]` it again? Always possible I suppose. – Mooing Duck Mar 16 '15 at 19:17
  • 1
    @MooingDuck I mean that the string inside a `std::string` object should be considered constant when using raw pointers, using non-constant C-style pointer allows the function to modify the string which might not work well with the `std::string` object. For example, what if the function truncates the string by setting the string terminator, that won't be reflected by the `std::string` object. – Some programmer dude Mar 16 '15 at 19:19
0

Here's a sample conversion code:

#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;}

Output:

Pc
Jahid
  • 21,542
  • 10
  • 90
  • 108