Insert variable directly into string

Hi all, I was wondering what the C++ equivalent of the below Python code would be?

1
2
3
4
5

ht = 10

e = 'FT{}\r\n'.format (ht)


ie, if you wanted to insert a variable directly into the 'word' of a string, rather than just 'in between words' This code would give e = FT10

Any tips appreciated. Thank you
Try this:
1
2
int ht {10};
string e {"FT"+std::to_string(ht)};
you have options..

c++ handles this oddly, through another object called a stringstream, which is sort of a step backwards or sidways to what should be allowed. https://www.cplusplus.com/reference/sstream/stringstream/stringstream/
this gives you all the control of cout formatting.

also consider
int ht = 42;
double d = 3.1415
string s = "int is "+std::to_string(ht)+" and double is "+ std::to_string(d);
to_string does not give you any control over the formatting.

you can also do it with C code, via sprintf, and microsoft's CString also supports it directly as that is a thin object over C. These have a simple and easy to use formatting.

Last edited on
Thank you!
As C++20:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <format>

int main() {
	constexpr int ht {10};

	const auto e {std::format("FT{:d}", ht)};

	std::cout << e << '\n';
}



FT10

Thank you
Topic archived. No new replies allowed.