Insert variable directly into string
Oct 5, 2021 at 2:33pm UTC
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
Oct 5, 2021 at 2:52pm UTC
Try this:
1 2
int ht {10};
string e {"FT" +std::to_string(ht)};
Oct 5, 2021 at 2:53pm UTC
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 Oct 5, 2021 at 2:56pm UTC
Oct 5, 2021 at 2:54pm UTC
Thank you!
Oct 5, 2021 at 3:34pm UTC
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' ;
}
Oct 5, 2021 at 4:13pm UTC
Thank you
Topic archived. No new replies allowed.