+ 1

How to do string formating in c++?

in Python x = [1, 2, 3, 66, 599, 79) print("{} | {} | {}".format(x[1], x[2], x[3]) I have to do print the same value using c++ is there a way to do string formating in c++ just like Python?

12th Oct 2018, 10:22 AM
Sainath Dora
Sainath Dora - avatar
11 Answers
+ 1
You have to use the printf - function instead of cout, like (not only I) showed with an example. You basically only have to copy-paste it.
12th Oct 2018, 1:06 PM
HonFu
HonFu - avatar
+ 1
Do you mean formatted output? Although, it's inherited from C, printf works similarly: printf("%d | %d | %d\n", x[1], x[2], x[3]); The above will give the same output. See the <cstdio> header.
12th Oct 2018, 11:29 AM
non
+ 1
dude thanks a lot!!😱😱
12th Oct 2018, 1:11 PM
Sainath Dora
Sainath Dora - avatar
0
Not exactly like that, but comparable, for example: printf("%s is a string of length %i.", "Hello!", 6); % is like {}, and the next letter is a required datatype marker (string, int). Then behind the string you add the number of arguments equal to the number of %.
12th Oct 2018, 11:27 AM
HonFu
HonFu - avatar
0
#include <iostream> #include <cstdio> #include <string> using namespace std; int main() { string x[5] = {"a", "b", "c", "d", "e"}; cout << "%d | %d | %d\n", x[1], x[2], x[3]; } output is %d | %d | %d what should I do? BTW, I'm talking about c++ not c
12th Oct 2018, 12:54 PM
Sainath Dora
Sainath Dora - avatar
0
You haven't written what we suggested. How about you try that? (Works in C++! )
12th Oct 2018, 1:01 PM
HonFu
HonFu - avatar
0
I didn't understood you could you show me?
12th Oct 2018, 1:03 PM
Sainath Dora
Sainath Dora - avatar
0
what?! never heard that there's a printf function in c++ if this works thanks
12th Oct 2018, 1:08 PM
Sainath Dora
Sainath Dora - avatar
0
You can use a lot of what c has by including the right header files (when there's nothing better in c++).
12th Oct 2018, 1:10 PM
HonFu
HonFu - avatar
0
one more thing can we use printf instead of cout? cause even using printf I printed hello world
12th Oct 2018, 1:13 PM
Sainath Dora
Sainath Dora - avatar
0
Often there are several ways to do a thing (as in Python you could also use 'sys.stdout.write()' instead of 'print'). So if the function does what you want it to do, I'd just use it. (If there's problems with this, now would be the moment for more experienced C++ people to chime in. ;))
12th Oct 2018, 1:22 PM
HonFu
HonFu - avatar