+ 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?
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.
+ 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.
+ 1
dude thanks a lot!!😱😱
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 %.
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
0
You haven't written what we suggested. How about you try that?
(Works in C++! )
0
I didn't understood you could you show me?
0
what?!
never heard that there's a printf function in c++
if this works thanks
0
You can use a lot of what c has by including the right header files (when there's nothing better in c++).
0
one more thing
can we use printf instead of cout?
cause even using printf I printed hello world
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. ;))