Pregunta

I was looking for solutions to appending strings with other primitives and found that stringstream was the easiest solution. However, I wanted to streamline the process so I wanted to make a function to ease its use. In case you are proposing alternate methods for concatenation, i need the final result to be char*. I used a loop (i) with:

std::stringstream ss;
ss << "test" << i;      
char* name = new char[ss.str().size() + 1];//allocate
strcpy(name, ss.str().c_str());//copy and put (char*)c_str in name

So the output is something link test1test2test3... This was the most reasonable solution I could muster. I was trying to put it into a function for ease of use, but am running into problems. I wanted to do something like:

char* string_to_pointer( char* dest, std::stringstream* _ss ) {
   char* result = new char[_ss->str().size() + 1];
   strcpy(result, _ss->str().c_str());
   return result;
}

I could then do something like:

std::stringstream ss;
ss << "test" << i;      
char* name = string_to_pointer( name, &ss );

I'm pretty new to c++ and this seems like the correct use syntactically, but I am running into runtime issues and would welcome solutions on how to get this in an easy to use function without resulting to Boost.

¿Fue útil?

Solución 2

Use the std::stringstream::str() function to retrieve the contents of the string.

Example:

int foo = 42;
double bar = 12.67;

std::stringstream ss;
ss << "foo bar - " << foo << ' ' << bar;

std::string result = ss.str();

If you dont want to modify the string further, you can now simple call result.c_str() to acquire a const char*. However, if you really need a modifyable char* you have to copy the contents of the string to a cstring:

std::unique_ptr<char[]> cstring = new char[result.size() + 1];
strcpy(cstring.get(), result.c_str());

Otros consejos

What about something like this:

#include <string>
#include <sstream>

class ToString {
  std::ostringstream stream;
public:
  template<typename T>
  inline ToString &operator<<(const T&val) {
    stream << val;
    return *this;
  }

  inline operator std::string() const {
    return stream.str();
  } 
};

You can use it like this:

std::string str = ToString() << "Test " << 5 << " and " << 4.2;
char* string_to_cstring ( const std::string &_ss )

Would be cleaner! Use with string_to_cstring(ss.str())

Need the returned C-String to be changeble? Because if not, just use ss.str().c_str() wherever you need it!

Or use:

char* result = new char[ss.str().size() + 1] (); // value initialized
ss.str().copy(result,std::string::npos);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top