C++ std::string concatenation
Append one string to another to assemble a printable identifier.
A simple example
std::string concatenation
- Start with "a" and "b"
- Do this Join end to end
- Result "ab"
#include <iostream>
#include <string>
int main() {
const std::string value = "a";
const std::string other = "b";
std::cout << (value + other) << "\n";
return 0;
}
ab
Syntax
value + other
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonAttach a seat number to a row
A label printer receives an identifier in separate pieces instead of one finished string. Assemble the pieces in the intended order and check the separator where the two fields meet.
#include <iostream>
#include <string>
int main() {
const std::string value = "Row B-";
const std::string other = "12";
std::cout << (value + other) << "\n";
return 0;
}
Row B-12
The prefix already contains the hyphen.
Add an extension to a receipt
An export routine receives the base name for a receipt. Add the extension to produce the printable filename and keep the original name available for any other export format.
#include <iostream>
#include <string>
int main() {
const std::string value = "march";
const std::string other = ".pdf";
std::cout << (value + other) << "\n";
return 0;
}
march.pdf
The extension includes its own leading dot.
Build a parcel shelf identifier
The shelf prefix already includes the hyphen. Combine the two fragments in order without adding another separator. What label goes to the printer?
What to watch for
Insert any required separator explicitly. Keep the returned text in languages with immutable strings.