Reputation: 7222
I am relatively new to the C++ world.
I know std::cout
is used for console output in C++. But consider the following code in C :
#include<stdio.h>
int main(){
double dNum=99.6678;
printf("%.02lf",dNum);
//output: 99.67
return 0;
}
How do I achieve the similar formatting of a double type value upto 2 decimal places using cout
in C++ ?
I know C++ is backward compatible with C. But is there a printf() equivalent in C++ if so, then where is it defined ?
Upvotes: 8
Views: 22770
Reputation: 55494
But is there a printf() equivalent in C++ if so, then where is it defined?
C++23 added a similar formatting facility to C++ called std::print
:
import std;
int main()
std::print("{:.02f}", 99.6678);
}
On older systems you can use the {fmt} library, std::print
is based on:
#include <fmt/core.h>
int main()
fmt::print("{:.02f}", 99.6678);
}
std::print
and {fmt} use Python-like format string syntax which is similar to printf
's except for {}
delimiters instead of %
.
std::print
preserves the type information so it is fully type-safe and doesn't need l
and similar specifiers that convey type.
Disclaimer: I'm the author of {fmt} and C++23 std::print
.
Upvotes: 3
Reputation: 14390
If you want to use printf
like formatting you should probably use snprintf
(or build an allocating variant of that on top of that). Note that sprintf
requires you to be able to guarantee that the result will not overrun the buffer you have to keep defined behaviour. With snprintf
on the other hand can guarantee that it will not overrun the buffer since you specifiy the maximal number of characters that will be written to the string (it will instead truncate the output).
You could even build something that can directly be fed to an ostream
on top of snprintf
by automatically allocate the buffer and place in an object that on destruction free that memory. This in addition with a method to feed the object to an ostream
would finish it off.
struct FMT {
char buf[2048];
FMT(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
}
};
inline std::ostream& operator<< (std::ostream& os, FMT const& str) { os << (const char*)str.buf; return os; }
then you use this as:
cout << FMT("The answer is %d", 42) << endl;
If you're using the GNU libraries you could of course use printf
directly since cout
and stdout
are the same object then. Otherwise you should probably avoid mixing stdio
and iostreams
as there is no guarantee that these are synchronized with each other.
Upvotes: 2
Reputation: 5186
There is no equivalent. It is a pain using cout
for formatted output.
All suggested solutions calling setprecision
and similar are awfull when using long formats.
boost::format
does not support some very nice features. Incompatibilities with printf. I still use printf
because it is unbeatable.
Upvotes: 8
Reputation: 2391
This is what you want:
std::cout << std::fixed << std::setprecision(2);
std::cout << dNum;
and don't forget to :
#include <iostream>
#include <iomanip>
Upvotes: 13
Reputation: 36597
The functional equivalent of your printf()
call, using std::cout
, is
std::cout << fixed << setprecision(2) << dNum;
It is necessary to #include
<iomanip>
and <iostream>
.
The printf()
equivalent in C++ is std::printf()
, declared in <cstdio>
.
Also, thanks to backward compatibility to C - specifically C++98 was required to maximise backward compatiblility to C89 - C's printf()
declared in <stdio.h>
is also available in C++. Note, however, that <stdio.h>
is deprecated (tagged for removal from a future version of the C++ standard). Also, not all features of printf()
introduced in C99 (the 1999 C standard) or later are necessarily supported in C++.
Upvotes: 0
Reputation: 1123
To output a value to the console using C++, you need the global ostream object cout and the << operator. endl is another global ostream object used as line break.
All are defined in the <iostream>
header file. You can also use various formatting flags to control the presentation of the output...
#include<iostream>
using namespace std;
int main() {
double dNum = 99.6678;
cout << dNum;
cout.setf(ios::scientific, ios::floatfield); // format into scientific notation
cout << dNum;
cout.precision(8); // change precision
cout << dNum;
system("pause");
return 0;
}
Upvotes: 0
Reputation: 1528
If you really want to reuse the same formatting techniques as in C, you may use Boost::format, which does exactly that:
cout << boost::format("%.02lf") % dNum;
Upvotes: 2
Reputation: 4647
You can also use sprintf in C++ to 'print' into a string and then cout that string. This strategy leverages your experience with printf-style formatting.
Upvotes: 0
Reputation: 5629
Save your program as CPP
and run it.
It runs and prints the answer.
Because C++ also has the printf()
and scanf()
like C
.
Upvotes: 0