How to concatenate "constant lines" and characters?

What is the “right way” to do the following? (Note: I do not want to display a message on the screen (yet), the data should be stored in a variable.)

std::cout << "Enter a letter: ";    
char input;
std::cin >> input;

std::string message = "Today program was brought to you by the letter '" + input + "'.";

The code gives me an error message with invalid type operands const char*and const char [3]binary operator+.

I understand why this message is happening. When googling for a solution, the results that appear recommend throwing each element in a row in turn. However, this becomes impractical if you need to combine a dozen elements:

std::string("x:") + x + std::string(", y:") + y + std::string(", width:") + width + std::string(", height:") + height + ...;

What is the “correct way” in C ++ to concatenate strings, characters, char arrays, and any other data that can be converted into one string? Is there something like Python that beautiful string formatting functions in C ++?

+4
source share
2 answers

What you are trying to do will not work, because C ++ treats your concatenation as an attempt to add multiple pointers char. If you explicitly applied the first element in the series to std::string, it should work.

Change the source code

string message = "Today program was brought to you by the letter '" + input + "'.";

:

string message = std::string("Today program was brought to you by the letter '")
    + input + "'.";

qv is this SO post which discusses this issue in more detail (although I don’t know why it closed because it is not a question).

+4

, "", std::stringstream :

string message = formatter() << "Today program was brought to you by the letter '" << input << "'.";

:

#include <sstream>

class formatter {
public:
    template <typename T>
    formatter & operator<<(const T & o) {
        stream_ << o;
        return *this;
    }

    const std::string str() const { return stream_.str(); }

    operator std::string() {
            return stream_.str();
    }

private:
    std::ostringstream stream_;
};

: std::stringstream() formatter() , ,

  • std::stringstream std::string
  • std::string message = (std::stringstream() << "foo" << input << "bar").str();, std::stringstream std::ostream & ( std::stringstream &), ostream string .

formatter stringstream .

+2

All Articles