C++ create string of text and variables

2019-02-02 21:10发布

问题:

I'm trying to do something very simple and yet, after an hour of so of searching a I can't find a suitable answer so I must be missing something fairly obvious.

I'm trying to dynamically create filenames for use with ifstream. Whilst I understand various methods are available of doing this, I have settled on creating a std::string, and the using stringname.c_str to convert to const.

The problem is however that I need to create the string with a mix of variables and predefined text values. I'm getting compiler errors, so this must be a syntax issue.

Pseudo

std::string var = "sometext" + somevar + "sometext" + somevar;

Thanks!

回答1:

Have you considered using stringstreams?

#include <string>
#include <sstream>

std::ostringstream oss;
oss << "sometext" << somevar << "sometext" << somevar;
std::string var = oss.str();


回答2:

std::string var = "sometext" + somevar + "sometext" + somevar;

This doesn't work because the additions are performed left-to-right and "sometext" (the first one) is just a const char *. It has no operator+ to call. The simplest fix is this:

std::string var = std::string("sometext") + somevar + "sometext" + somevar;

Now, the first parameter in the left-to-right list of + operations is a std::string, which has an operator+(const char *). That operator produces a string, which makes the rest of the chain work.

You can also make all the operations be on var, which is a std::string and so has all the necessary operators:

var = "sometext";
var += somevar;
var += "sometext";
var += somevar;


回答3:

In C++11 you can use std::to_string:

std::string var = "sometext" + std::to_string(somevar) + "sometext" + std::to_string(somevar);  


回答4:

See also boost::format:

#include <boost/format.hpp>

std::string var = (boost::format("somtext %s sometext %s") % somevar % somevar).str();


回答5:

You can also use sprintf:

char str[1024];
sprintf(str, "somtext %s sometext %s", somevar, somevar);