Search code examples
c++stringcharstring-concatenation

How do I concatenate strings with chars in C++?


I've got a function which takes a string, let's call it

void print(std::string myString) 
{ 
    std::cout << myString;
}

I want to do something like

char myChar;
myChar = '{';
print("Error, unexpected char: " + myChar + "\n");

It doesn't work.

I tried something like

print(std::string("Error, unexpected char") + std::string(myChar) + std::string("\n) )

but then std::string(myChar) becomes whatever int the char represents, it's printed as an int and isn't printed as it's alphanumeric representation!


Solution

  • The function should be declared like:

    void print( const std::string &myString) 
    { 
        std::cout << myString;
    }
    

    and called like:

    print( std::string( "Error, unexpected char: " ) + myChar + "\n");
    

    As for your comment:

    as a follow up, would it have been possible to pass an anonymous function returning a string as an argument to print()? Something like print( {return "hello world";}

    then you can do this as it is shown in the demonstration program:

    #include <iostream>
    #include <string>
    
    void f( std::string h() )
    {
        std::cout << h() << '\n';
    }
    
    int main() 
    {
        f( []()->std::string { return "Hello World!"; } );
        
        return 0;
    }