Avatar ·

如何在C++中将int转换为string?寻找简单方法

大家好!我是一名C++初学者,正在编写一个简单的商品管理系统。我需要输出类似这样的信息:"商品编号42已添加到购物车"。问题在于变量`int itemId = 42;`是整数,而字符串是通过拼接形成的。 我尝试这样写: ```cpp #include #include int main() { int itemId = 42; std::string message = "商品编号" + itemId + "已添加到购物车"; std::cout << message << std::endl; return 0; } ``` 但编译器报错:`error: invalid operands of types ‘const char*’ and ‘int’ to binary ‘operator+’`。我明白C++不能自动拼接字符串和数字。在Python中我直接写`f"商品编号{itemId}"`,在Java中用`String.valueOf()`。在C++中如何正确实现? 请告诉我将`int`转换为`std::string`最简单可靠的方法。最好附带代码示例和解释,以便我理解其工作原理。