Combining Numbers and Strings in C++

In C++, you may need to convert numbers to strings to concatenate them. This can be done using functions like std::to_string().

Using std::to_string()

Example: Converting Numbers to Strings

#include <iostream>
#include <string>

int main() {
    int year = 2023;
    std::string message = "Year: " + std::to_string(year);
    std::cout << message << std::endl;
    return 0;
}

Output:

Year: 2023

Key Takeaways

  • Use std::to_string() to convert numbers to strings.
  • Converting numbers allows for seamless concatenation with strings.
  • Be mindful of data types when performing concatenation.