appending int to string in cpp
To append an integer to a string in C++, you can follow these steps:
- Declare a string variable to store the initial string value.
- Declare an integer variable to store the integer value.
- Convert the integer value to a string using the to_string() function.
- Use the concatenation operator '+' to append the converted string to the initial string.
- The final value of the string will now contain the appended integer.
Please note that the example below demonstrates these steps:
#include <iostream>
#include <string>
int main() {
std::string initialString = "Hello";
int number = 42;
std::string appendedString = initialString + std::to_string(number);
std::cout << "Appended string: " << appendedString << std::endl;
return 0;
}
This program declares a string variable initialString
with the value "Hello" and an integer variable number
with the value 42. It then uses the concatenation operator '+' to append the string representation of number
to initialString
. The resulting string is stored in the appendedString
variable. Finally, the program prints the value of appendedString
to the console, which will be "Hello42".