如何在 C++ 中连接字符串和字符?

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

我有一个接受字符串的函数,我们称它为

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

我想做类似

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

没用。

我试过

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

但随后 std::string(myChar) 变成 char 代表的任何 int,它被打印为 int 而不是打印,因为它是字母数字表示!

函数应该这样声明:

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

并称呼为:

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

关于您的评论:

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

那么你就可以按照演示程序中所示的方式进行操作了:

#include <iostream>
#include <string>

void f( std::string h() )
{
    std::cout << h() << '\n';
}

int main() 
{
    f( []()->std::string { return "Hello World!"; } );
    
    return 0;
}

您可以转换任何一个并连接。

您可以使用 str.c_str() 将 C++ 字符串转换为 C 字符数组。

使用 std::string 内置构造函数将 C 字符数组转换为 C++ 字符串。

如果你使用的是 C++14,你可以这样做:

using namespace std::literals;
char myChar;
myChar = '{';
print("Error, unexpected char: "s + myChar + "\n"s);