How to convert int to string in C++? Looking for a simple way
Hello everyone! I'm a beginner C++ developer writing a simple product tracking program. I need to display a message like: "Product number 42 added to cart". The problem is that the variable `int itemId = 42;` is an integer, and the string is formed through concatenation.
I tried writing like this:
```cpp
#include
#include
int main() {
int itemId = 42;
std::string message = "Product number " + itemId + " added to cart";
std::cout << message << std::endl;
return 0;
}
```
But the compiler gives an error: `error: invalid operands of types ‘const char*’ and ‘int’ to binary ‘operator+’`. I understand that C++ cannot automatically add strings and numbers. In Python I just wrote `f"Product number {itemId}"`, and in Java I used `String.valueOf()`. How to do it correctly?
No answers yet.
Log in to leave an answer
Blogs